Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist
View gist:1640639
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
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
Owner

Another solution would be actually using ruby eval instead of define_method, which is probably more efficient and maybe even more clear code, but I have an instinctive irrational desire to always avoid eval. But the eval approach is I think what I've seen in for instance Rails source that does things similar to this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.