Catching Errors in Ruby
I have a statement that looks something like this
if not @user.verified? or @user.credit_card.expired?
# do stuff
end
The problem is the ca开发者_StackOverflowse where the @user
does not yet have a credit card because expired?
will raise an exception because of the nil value.
Is there a succinct way to catch the error inline without having to resort to extra if statements?
To avoid this exception you can use Rails 2.3/3 built-in method: try
if not @user.verified? or @user.credit_card.try(:expired?)
# do stuff
end
The andand gem allows for a guarded method invocation if and only if the object is not null.
Your code snippet would look like this:
if not @user.verified? or @user.credit_card.andand.expired?
# do stuff
end
You can install it with gem install andand
and you're good to go.
Website: http://andand.rubyforge.org/
The code
@user.credit_card.expired?
Would be called a violation of the Law of Demeter. That law states you're allowed to call any method you like on @user
, but not on @user.credit_card
.
精彩评论