Xero
Xero

Reputation: 4173

Better ternary condition

Method find_something may return nil. In the following code,

something = find_something(id) ? find_something(id) : create_something(foo)

find_something(id) is called twice. This is a smell that I want to avoid. Is there a way to avoid redundancy in this expression?

Upvotes: 3

Views: 145

Answers (2)

SRack
SRack

Reputation: 12223

There's not quite enough detail given to say this with confidence, though it might be this is a case for find_or_create_by.

If this does suit, you would just do:

something = YourModel.find_or_create_by(id: id)

You can also provide a block to this, which is passed to the create method if no record is found. For example:

something = YourModel.find_or_create_by(id: id) do |instance|
  # this block only gets executed on create
  instance.some_new_attribute = 'goes here'
end

Hope that's useful - let me know if it suits your use case.

Upvotes: 6

Ursus
Ursus

Reputation: 30071

Anything like this?

something = find_something(id) || create_something(foo)

Upvotes: 10

Related Questions