Skip to content

Instantly share code, notes, and snippets.

@YaEvan
Forked from Bodacious/MethodMissing.rb
Created June 16, 2017 01:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YaEvan/dee242202f2e75621fe044ddce077157 to your computer and use it in GitHub Desktop.
Save YaEvan/dee242202f2e75621fe044ddce077157 to your computer and use it in GitHub Desktop.
Example of how to rewrite method_missing and respond_to? in Ruby
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment