Def or Not to Def
I needed some methods to return true/false if a attribute had a value. So, for example, we have a date attribute
#invited_on and I want an
#invited? method to return true if the date is present.
There are a few dates for which I need this.
My first attempt was to use
define_method to dynamically create the methods:
%w(invited_on selected_on confirmed_on ready).each do |attr| define_method attr.gsub('_on', '') + '?' do send(attr).present? end end
Someone can figure out what it does, but it isn’t “at a glance” readable.
I had to google
define_method to check how to use it.
Instead I could have just written out the methods:
def invited?; !!invited_on; end def selected?; !!selected_on; end def confirmed?; !!confirmed_on; end def ready?; !!ready_on; end
Readable at a glance.
If I was to add further dates there would be a temptaion to DRY it up with a
bit of meta programming like the original use of
define_method, but I might
argue that being readable and explicit is preferable.