Last active
December 22, 2015 18:49
-
-
Save sidraval/6515881 to your computer and use it in GitHub Desktop.
Sometimes, an options hash is better than a bunch of instance variables. But referring to things like options[:key] is annoying, as is setting things via options[:key] = ... Enter method_missing.
This file contains 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
# If your options hash is stored in @options | |
attr_accessor :options | |
def method_missing(meth,*args,&prc) | |
if options.keys.include?(meth.to_sym) | |
options[meth.to_sym] | |
elsif options.keys.include?(meth[0...-1].to_sym) && meth[-1] == "=" | |
options[meth[0...-1].to_sym] = args.first | |
else | |
super | |
end | |
end | |
########## EXAMPLE USE ########## | |
class Cat | |
attr_accessor :options | |
def initialize | |
@options = {firstname: "Octo", lastname: "Cat"} | |
end | |
def method_missing(meth,*args,&prc) | |
if options.keys.include?(meth.to_sym) | |
options[meth.to_sym] | |
elsif options.keys.include?(meth[0...-1].to_sym) && meth[-1] == "=" | |
options[meth[0...-1].to_sym] = args.first | |
else | |
super | |
end | |
end | |
end | |
octocat = Cat.new | |
# => #<Cat:0x007f98658315f8 @options={:firstname=>"Octo", :lastname=>"Cat"}> | |
octocat.firstname | |
# => "Octo" | |
octocat.firstname = "Septa" | |
# => "Septa" | |
octocat | |
# => #<Cat:0x007f98658315f8 @options={:firstname=>"Septa", :lastname=>"Cat"}> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment