Last active
May 11, 2017 16:35
-
-
Save wconrad/ba8743be14dd5f30723654e25440f3ca to your computer and use it in GitHub Desktop.
Method missing example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Exmaple using method_missing to expose dynamic attributes. | |
class Foo | |
def initialize | |
@attrs = {:a => 1, :b => 2} | |
end | |
def method_missing(method, *args, &block) | |
if @attrs.has_key?(method.to_sym) | |
send(:[], method, *args) | |
else | |
super | |
end | |
end | |
# When you override method_missing, it's good manners to override | |
# respond_to? as well. You can often get away without it. | |
def respond_to?(method) | |
super || @attrs.has_key?(method.to_sym) | |
end | |
private | |
# This can be public if you want there to be another way to fetch an | |
# attribute. The reason it exists is to get us cheap and easy | |
# checking for the number of arguments passed into method_missing. | |
def [](attr_name) | |
@attrs.fetch(attr_name.to_sym) | |
end | |
end | |
foo = Foo.new | |
p foo.a # => 1 | |
p foo.b # => 2 | |
p foo.respond_to?(:a) # => true | |
p foo.respond_to?(:z) # => false | |
p foo.a(2) # => wrong number of arguments | |
p foo.c # => undefined method 'c' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment