Can I do this in Ruby?
Currently I have the following 2 lines of code
errors.add_to_base I18n.t :error_message if value != 1
return false if !errors.blank?
Is it possible to condense t开发者_如何学运维his into 1 line of code? I need to do this in multiple places with different error message and condition. Also, "return false" is to stop the flow of an ActiveRecord lifecycle.
Hmm. If you know errors.blank?
will be true unless the first condition fires then:
(errors.add_to_base I18n.t :error_message; return) if value != 1
Update: Aha, you are willing to define a method. How about a Proc
object? It's better than a method here in that if the Proc
block returns then the invocation will return from the surrounding method.
test = Proc.new do |cond, msg|
errors.add_to_base I18n.t msg if cond
return unless errors.blank?
end
# ...
test.call value != 1, :error_message
Note that you don't need to return false
as a plain return
will return nil
and that will be good enough unless some sadist is doing something like f().class == NilClass
. :-)
You can take advantage of how the boolean logic operators work and do something like this:
value != 1 && errors.add_to_base I18n.t :error_message && return false
Not very clear, I wouldn't recommend using it. Also if errors.add_to_base
returns something that's "falseish" the return false wouldn't happen.
Remember: "Always code as if the person who will maintain your code is a violent psychopath who knows where you live”
精彩评论