我定义了以下内容:
#!/usr/bin/env ruby
class Something
def self._attr_accessor key, value, type
(class << self; self; end).send( :attr_accessor, key.to_sym)
instance_variable_set "@#{key}", value
end
end
class Client < Something
_attr_accessor 'foo_bar', 'json', String
end
my_something = Client.new
puts my_something.foo_bar
但我收到以下错误:
/test_inheritance.rb:18:in `<class:Client>': undefined method `foo_bar' for Client:Class (NoMethodError)
from ./test_inheritance.rb:14:in `<main>'
我正在做的一些元编程工作:
#!/usr/bin/env ruby
class Something
def self._attr_accessor key, value, type
(class << self; self; end).send( :attr_accessor, key.to_sym)
instance_variable_set "@#{key}", value
end
end
class Client < Something
_attr_accessor 'foo_bar', 'json', String
puts self.foo_bar
end
my_something = Client.new
#puts my_something.foo_bar
因为它输出正确的结果。但是如何定义 _attr_accessor 方法以便我能够公开访问它?