4
\$\begingroup\$

I want to check if a record already exists in a database, and return true or false.

If it exists, I want to update the update_at datetime field. The method touch_with_version from the paper_trail gem will do it.

Which is better?

  def repeated?(unprocessed)
    occurrence = Occurrence.find_by(unprocessed: unprocessed)
    occurrence.touch_with_version if occurrence.present?
    occurrence.present?
  end

Or

  def repeated?(unprocessed)
    occurrence = Occurrence.find_by(unprocessed: unprocessed)

    if occurrence.present?
      occurrence.touch_with_version
      true
    else          
      false
    end        
  end

Is there a better way?

\$\endgroup\$
5
\$\begingroup\$

When working within a Rails environment you can use try

occurrence.try(:touch_with_version)
occurrence.present?

Ruby also provides tap so you could also write:

occurrence.tap({|o| o.try(:touch_with_version)}).present?

You could even dig into the libraries to see that touch_with_version returns the result of ActiveRecord's save! which in turn returns the result of create_or_update which returns a boolean and so you can write:

occurrence.try(:touch_with_version).present?

If you're happy returning true, false, or nil you could shorten it to:

occurrence.try(:touch_with_version)

Very nice but also more fragile if either of those libraries decide to change their return values in a future release.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.