Last Updated: February 25, 2016
·
979
· ianrgz

Refactoring method definitions

Lets say we have a class where we have 3 methods:

class Messages
  def draft
    @status = :draft
  end

  def posted
    @status = :posted
  end

  def deleted
    @status = :deleted
  end
end

As we can see the three methods are just updating the value of our instance variable '@status', we can refactor this by taking advantage of definemethod, we first need to create a states array and iterate through it, then inside the block we call definemethod to dynamically create our methods like so:

class Messages
  states = [:draft, :posted, :deleted]

  states.each do |state|
    define_method state do
      @status = state
    end
  end
end

There we go, much cleaner an it runs exactly the same, now if we wanted to create new methods we just need to add them to the states array, hope you find it useful.

1 Response
Add your response

I like the way Ruby makes this kind of magic a piece of cake... Thanks for the tip! It becomes easy to add new states without having to add the corresponding methods by hand.

over 1 year ago ·