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
endAs 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
endThere 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.
Written by Ian Rodriguez
Related protips
1 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
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
 #Ruby 
Authors
Related Tags
#ruby
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#

 
 
 
 
