Dynamic Method Definition

You have methods that can be defined more concisely if defined dynamically.

Define the methods dynamically.

def failure
  self.state = :failure
end

def error
  self.state = :error
end 

image/svg+xml

def_each :failure, :error do |method_name|
  self.state = method_name
end 

Additions

Martin Fowler

8 Nov 2013

A problem with dynamic method definition is that it can make it harder to search for method definitions. Usually in Ruby you can search for "def method_name" in order to find where methods are defined (or to be safer use a regex like /def\s+methodName/). Any dynamic method definitions will not show up to a search like this. If you use a consistent list-oriented definition method (such as def_each in the book) you can find dynamic method definitions - at the cost of a more complex regex.