Created
October 2, 2010 15:12
-
-
Save trevmex/607711 to your computer and use it in GitHub Desktop.
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
| 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