public
Last active

Example of how to rewrite method_missing and respond_to? in Ruby

  • Download Gist
MethodMissing.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
class CarPart
 
# does the method name end in _price ?
def ghost_method_condition(name)
!!name.to_s[/_price$/]
end
# rewrite method missing if the method matches ghost_method_condition
def method_missing(name, *args, &block)
super unless ghost_method_condition(name)
# do something else...
end
 
# rewrite respond_to? to include ghost methods
def respond_to?(name, include_private = false)
ghost_method_condition(name) || super
end
 
end
c = CarPart.new
puts c.respond_to? :stereo_price

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.