Blocks
Build a big expertise of Ruby –
One small block of knowledge at a time.
Method Missing
Dynamic Method Handling in Ruby
The method_missing
hook allows you to handle calls to undefined methods. It's perfect for creating dynamic APIs and implementing flexible interfaces.
class User
def method_missing(method_name, *args)
if method_name.to_s.start_with?('find_by_')
attribute = method_name.to_s.split('find_by_').last
where(attribute => args.first)
else
super
end
end
end
# Now you can do:
User.find_by_name("John")
Great for creating dynamic finders, API wrappers, and configuration objects. Remember to implement respond_to_missing?
and always call super
for unhandled methods.
Level 1: Metadata