如何在Rails中实现业务规则?
我有一组需要强制执行的业务规则,例如:
- 如果 current_user 不是“admin”,则不允许并给出消息“限制访问”
- 如果问题已得到解答,则不允许另一个答案并给出消息“问题已得到解答”
现在,所有这些基本上都是:“如果 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:
- If current_user is not "admin" then don't allow and give message "restricted access"
- 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有多种方法可以实现此目的,但最好的方法可能是使用内置的 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