public
Created

  • Download Gist
gistfile1.rb
Ruby
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

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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.