Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
@jrochkind
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.