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 f开发者_StackOverflow社区alse,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
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
精彩评论