Skip to content

Instantly share code, notes, and snippets.

@sidraval
Last active December 22, 2015 18:49
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 sidraval/6515881 to your computer and use it in GitHub Desktop.
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.
# 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