This is how attr_writer may be (re)implemented:
module Kernel
def attribute_writer(attribute)
define_method("#{attribute}=".to_sym) do |value|
instance_variable_set("@#{attribute}", value)
end
end
end
class MyClass
attribute_writer :my_attribute
end
m = MyClass.new
m.my_attribute = 23
puts m.instance_variable_get "@my_attribute" # => 23
Thanks for the post! I got a wrong number of arguments exception when I tried to add more than one attribute like this:
attribute_writer :one, :two
I modified attribute_writer to take an arbitrary number of arguments:
def attribute_writer(attr1, *rest)
rest << attr1
rest.each do |attribute|
define_method("#{attribute}=".to_sym) do |value|
instance_variable_set("@#{attribute}", value)
end
end
end