Bob
Bob

Reputation: 8504

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 this 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.

Upvotes: 1

Views: 97

Answers (2)

DigitalRoss
DigitalRoss

Reputation: 146281

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. :-)

Upvotes: 1

Chris Cherry
Chris Cherry

Reputation: 28574

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”

Upvotes: 1

Related Questions