Created
January 19, 2012 15:37
-
-
Save jrochkind/1640639 to your computer and use it in GitHub Desktop.
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
module MyAccessors | |
def my_attr_accessor(property_name) | |
send(:define_method, property_name) do | |
instance_variable_get("@#{property_name}") | |
end | |
send(:define_method, "#{property_name}=") do |value| | |
instance_variable_set("@#{property_name}", value) | |
end | |
end | |
end | |
class Foo | |
extend MyAccessors | |
my_attr_accessor :foo | |
end | |
obj = Foo.new | |
obj.foo # => nil, no exception | |
obj.foo = 12 | |
obj.foo # => 12 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another solution would be actually using ruby
eval
instead ofdefine_method
, which is probably more efficient and maybe even more clear code, but I have an instinctive irrational desire to always avoideval
. But theeval
approach is I think what I've seen in for instance Rails source that does things similar to this.