如果要一边声明一边初始化可以用这样的代码:
[code]
class Object
def better_accessor(attrs)
(class << self; self; end).send :attr_accessor, *attrs.keys
attrs.each {|k,v| instance_variable_set("@#{k}", v)}
end
end
[/code]
然后就可以这样用:
[code]
class Test
def intialize
better_accessor :foo =>'bar' #初始化值即定死(值的正确性就自己保证了,用户只能通过setter改)
end
end
t = Test.new
t.foo #=> 'bar'
[/code]
或者先建对象后加属性,不用先定死值,但是用户可以在声明时绕过可能的setter验证,不安全:
[code]
t2 = Object.new
t2.better_accessor :hello =>'world'
t2.hello #=> 'world'
[/code]
[code]
class Object
def better_accessor(attrs)
(class << self; self; end).send :attr_accessor, *attrs.keys
attrs.each {|k,v| instance_variable_set("@#{k}", v)}
end
end
[/code]
然后就可以这样用:
[code]
class Test
def intialize
better_accessor :foo =>'bar' #初始化值即定死(值的正确性就自己保证了,用户只能通过setter改)
end
end
t = Test.new
t.foo #=> 'bar'
[/code]
或者先建对象后加属性,不用先定死值,但是用户可以在声明时绕过可能的setter验证,不安全:
[code]
t2 = Object.new
t2.better_accessor :hello =>'world'
t2.hello #=> 'world'
[/code]