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.