Skip to content

Instantly share code, notes, and snippets.

@tobiashm
Last active January 4, 2017 20:40
Show Gist options
  • Save tobiashm/7eb7931cb085ee93e33703be4f667799 to your computer and use it in GitHub Desktop.
Save tobiashm/7eb7931cb085ee93e33703be4f667799 to your computer and use it in GitHub Desktop.
Ruby special behaviour: `respond_to_missing?` method gets hidden
# When you implement `method_missing` you should also implement `respond_to_missing?`
# But the later doesn't show up as instance methods on the class, and can not be called directly! Or does it???
class Foo
def method_missing(name, *)
"called #{name}"
end
def bar?
respond_to_missing?(:bar)
end
# Defined as private in `Object`
def respond_to_missing?(*)
true
end
end
Foo.instance_methods(false) # => [:method_missing, :bar?]
foo = Foo.new
foo.bar # => "called bar"
foo.respond_to? :bar # => true
foo.respond_to_missing? :bar # => "called respond_to_missing?"
foo.private_methods(false) # => [:respond_to_missing?]
foo.send(:respond_to_missing?) # => true
foo.bar? # => true
@tobiashm
Copy link
Author

tobiashm commented Jan 4, 2017

Updated: I had some weird issues where I wasn't able to call respond_to_missing? even from other methods in the class. But it all seems to work now 😕

@tobiashm
Copy link
Author

tobiashm commented Jan 4, 2017

Updated update: I must have been calling self.respond_to_missing?!
See e.g. http://www.skorks.com/2010/04/ruby-access-control-are-private-and-protected-methods-only-a-guideline/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment