Skip to content

Instantly share code, notes, and snippets.

@jrochkind
Created January 19, 2012 15:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrochkind/1640639 to your computer and use it in GitHub Desktop.
Save jrochkind/1640639 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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