But when testing in the console I was always having to lookup a Person record to get the id, or sometimes I’d remember the ID. Wouldn’t it be nice if I could pass anything(within reason) and be able to ensure that I have a Person record?

[granted…this is Rails specific]

module Ensurable
extend ActiveSupport::Concern## ---# Allow you to ensure you have the class you expect... it's similar to# result = value.is_a?(Person) ? value : Person.find(value)## You can add fields to "ensure_by" (:id is included always)# e.g.# if you add `ensure_by :token` to the User class# User.ensure() works# User.ensure(:user_id) works# User.ensure(:token) works## .ensure() returns nil if the record is not found# .ensure!() throws an exception if the record is not found
class_methods dodef ensure_by(*args)@_ensure_by||= [:id]@_ensure_by+= [args].flattenenddefensure(thing = nil)returnnilunless thing.present?
return thing if thing.is_a?(self)
found = nil@_ensure_by||= [:id]@_ensure_by.eachdo|ensure_field|
value = thing.try(:fetch, ensure_field.to_sym, nil)|| thing.try(:fetch, ensure_field.to_s, nil)|| thing
found = self.find_by(ensure_field =&gt; value)breakif found.is_a?(self)end
found
enddefensure!(thing = nil)
result = self.ensure(thing)raiseActiveRecord::RecordNotFoundunless result
result
endendend