How Ruby finds methods
When you call object.method, Ruby climbs a chain: first the object's singleton class (home of methods only this object has), then its class, then the mixins, then the superclasses. You can display the chain:
oddball = "a normal string"
def oddball.shout
upcase + "!!!"
end
[oddball.shout, String.ancestors.first(4)]Because classes are objects themselves, code can create code – that's metaprogramming. define_method defines methods at runtime, send calls a method whose name sits in a variable:
class Config
def initialize(values)
@values = values
end
%w[host port language].each do |field|
define_method(field) { @values[field] }
end
end
c = Config.new({ "host" => "idogawa.com", "port" => 8011 })
[c.host, c.send("port")]That's exactly how Rails & co. build their macros like has_many or validates. An important warning from a wise fox: the cleverest code is often the first thing you delete later. There is a second way, too: method_missing catches every call for which Ruby finds no method. Whoever uses method_missing always writes respond_to_missing? as well – otherwise respond_to? tells lies – and passes everything the class doesn't know on with super:
class Settings
def initialize(values)
@values = values
end
def method_missing(name, *args)
key = name.to_s
return @values[key] if @values.key?(key)
super
end
def respond_to_missing?(name, include_private = false)
@values.key?(name.to_s) || super
end
end
s = Settings.new("theme" => "fox", "language" => "en")
[s.theme, s.respond_to?(:theme), s.respond_to?(:color)]Try s.color: super turns it into a perfectly ordinary NoMethodError. It works – but nobody sees such methods in the class, no documentation knows them, and a typo lands silently in method_missing. That's why an explicit define_method is almost always the clearer choice.
BaseModel.validates_presence_of(*fields) should use define_method to create a valid? method checking that none of the fields is nil or "". The class Booking below then uses it Rails-style.class BaseModel
# def self.validates_presence_of(*fields)
# define_method(:valid?) do
# ...
# end
# end
end
class Booking < BaseModel
attr_accessor :project, :hours
# validates_presence_of :project
end