What are #method_missing and #send? Why are they useful?
method_missing, as the name suggests, is called when the method cannot be found. With this powerful meta-programming tool, we can create dynamic methods, such as the dynamic finder in Active Record class Legislator Send is also a powerful tool for dynamic method invocation. Its function is to pass a method to the object in the form of parameters class Box def open_2 def open_3 def open_4 def open_5 box = Box.new box.send("open_#{num}")
# Pretend this is a real implementation
def find(conditions = {})
end
# Define on self, since it's a class method
def self.method_missing(method_sym, *arguments, &block)
# the first argument is a Symbol, so you need to_s it if you want to pattern match
if method_sym.to_s =~ /^find_by_(.*)$/
find($1.to_sym => arguments.first)
else
super
end
end
end
def open_1
puts "open box"
end
puts "open lock and open box"
end
puts "It's a open box"
end
puts "I can't open box"
end
puts "Oh shit box!"
end
end