#attr* 系列方法的简单非官方实现
class Class
def my_attr_reader(attr_name)
define_method(attr_name) do
instance_variable_get('@' + attr_name.id2name)
end
end
def my_attr_writer(attr_name)
define_method( (attr_name.id2name + '=').to_sym ) do |value|
instance_variable_set('@'+attr_name.id2name, value)
end
end
def my_attr_accessor(attr_name)
my_attr_reader(attr_name)
my_attr_writer(attr_name)
end
end
class MyClass
my_attr_accessor :params
end
myclass = MyClass.new
p myclass.params # => nil
myclass.params = 233
p myclass.params # => 233
#attr* 系列方法的简单非官方实现
class Class
def my_attr_reader(attr_name)
define_method(attr_name) do
instance_variable_get('@' + attr_name.id2name)
end
end
def my_attr_writer(attr_name)
define_method( (attr_name.id2name + '=').to_sym ) do |value|
instance_variable_set('@'+attr_name.id2name, value)
end
end
def my_attr_accessor(attr_name)
my_attr_reader(attr_name)
my_attr_writer(attr_name)
end
end
class MyClass
my_attr_accessor :params
end
myclass = MyClass.new
p myclass.params # => nil
myclass.params = 233
p myclass.params # => 233