Skip to content

Instantly share code, notes, and snippets.

@trevmex
Created October 2, 2010 15:12
Show Gist options
  • Select an option

  • Save trevmex/607711 to your computer and use it in GitHub Desktop.

Select an option

Save trevmex/607711 to your computer and use it in GitHub Desktop.
class Foo
def my_attr_accessor(*args)
args.each do |arg|
# def the_arg
# @the_arg
# end
self.instance_eval("def #{arg}; @#{arg}; end")
# def the_arg=(the_arg)
# @the_arg = the_arg
# end
self.instance_eval("def #{arg}=(#{arg}); @#{arg}=#{arg}; end")
end
end
def method_missing(method, *args)
if (/^set_/.match(method.to_s))
arg = method.to_s[4..method.to_s.length]
self.instance_eval("@attrs = {} if @attrs.nil?; @attrs['#{arg}'] = '#{args[0]}'")
elsif (/^get_/.match(method.to_s))
arg = method.to_s[4..method.to_s.length]
self.instance_eval("@attrs['#{arg}']")
else
super
end
end
end
f = Foo.new
f.my_attr_accessor :a, :b, :c
f.a = "hello"
f.a # <= "hello"
f.set_bob("steve")
f.get_bob
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment