如何在Rails中实现业务规则?

发布于 2024-10-09 03:54:32 字数 920 浏览 4 评论 0原文

我有一组需要强制执行的业务规则,例如:

  1. 如果 current_user 不是“admin”,则不允许并给出消息“限制访问”
  2. 如果问题已得到解答,则不允许另一个答案并给出消息“问题已得到解答”

现在,所有这些基本上都是:“如果 X 为假,则 Y 消息”。

所以,我做了这个方法:

def evaluate_rules rules
  rules.each_pair do |state,message|
    if not (state == true)
      return false,message
    end
  end
  true
end

本来应该这样调用:

evaluate_rules { 
  (1==1) => "good", #rule will pass
  (1==2) => "bad" #rule will fail
}

但是,我收到错误 syntax error, Unexpected tASSOC (SyntaxError) for the (1==1)(1==2) 哈希键。

如何将真/假值放入哈希键中?

另外,我忍不住认为以前可能有人已经解决了这个“规则”问题,有任何线索吗?

更新

已修复。 有时候,Ruby 会让我感到沮丧。 调用应该是这样的:

evaluate_rules Hash.new({ 
  (1==1) => "good", #rule will pass
  (1==2) => "bad" #rule will fail
})

看起来有点难看,但是可以用

I have a set of business rules that I need to enforce, such as:

  1. If current_user is not "admin" then don't allow and give message "restricted access"
  2. If question has been answered then don't allow another another answer and give message "question has already been answered"

Now, all these are basically: "if X is false then Y message".

So, I made this method:

def evaluate_rules rules
  rules.each_pair do |state,message|
    if not (state == true)
      return false,message
    end
  end
  true
end

Meant to be called like this:

evaluate_rules { 
  (1==1) => "good", #rule will pass
  (1==2) => "bad" #rule will fail
}

But, I get the error syntax error, unexpected tASSOC (SyntaxError) for the (1==1) and (1==2) hash keys.

How to put values of true/false into a hash key?

Also, I can't help but think someone may have solved this "rules" problem before, any leads?

UPDATE

Fixed.
Sometimes Ruby frustrates me.
The call should be like this:

evaluate_rules Hash.new({ 
  (1==1) => "good", #rule will pass
  (1==2) => "bad" #rule will fail
})

Looks a bit ugly but works

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

停顿的约定 2024-10-16 03:54:32

有多种方法可以实现此目的,但最好的方法可能是使用内置的 Rails 验证器。这些设置几乎可以完成您所描述的操作。在每个模型中,您可以创建验证,然后在验证失败时将消息添加到错误数组中。有许多内置验证,并且能够构建完全自定义的验证。这是我对上面列出的两个用例采取的方法。

这里有一些例子: http://omgbloglol.com/post/392895742/improved -validations-in-rails-3

There are several ways to accomplish this, but the best is probably to use the built-in Rails validators. These are setup to do pretty much what you're describing. In each model, you can create validations, that then add messages to an errors array if validation fails. There are a number of built in validations, and the ability to build completely custom ones. This is the approach I would take to the two use cases listed above.

Some examples here: http://omgbloglol.com/post/392895742/improved-validations-in-rails-3

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文