Skip to content

Instantly share code, notes, and snippets.

@krisleech
Created July 18, 2019 09:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krisleech/78d437d0e326700d0f59aeb3520e174e to your computer and use it in GitHub Desktop.
Save krisleech/78d437d0e326700d0f59aeb3520e174e to your computer and use it in GitHub Desktop.
Which is easier to read / maintain?

I need some methods to return true/false if a attribute had a value. So 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:

%w(invited_on selected_on confirmed_on ready).each do |attr|
  define_method attr.gsub('_on', '') + '?' do
    send(attr).present?
  end
end

I just wrote this, it is easy enough to figure out what it does, but it isn't at a glance readable. I also 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_to_start_on; end

Readable at a glance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment