Dex
Dex

Reputation: 12759

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 case 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?

Upvotes: 0

Views: 371

Answers (3)

Andrew Grimm
Andrew Grimm

Reputation: 81671

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.

Upvotes: 0

BitOfUniverse
BitOfUniverse

Reputation: 6021

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

Upvotes: 1

Paul Merrill
Paul Merrill

Reputation: 620

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/

Upvotes: 0

Related Questions