I have the following defined:
#!/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
But I recieve the following error:
/test_inheritance.rb:18:in `<class:Client>': undefined method `foo_bar' for Client:Class (NoMethodError)
from ./test_inheritance.rb:14:in `<main>'
The bit of metaprograming I am doing works:
#!/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
As it outputs the proper result. But how do I define the _attr_accessor methods such that I am able to access it methods publicly?
For one I think you’re tripping over the fact that
formatis a reserved method onClassand it’s conflicting with yourattr_accessorattempt.Secondly there’s a better way to do this. I’ve made a fairly robust “accessor” utility class for a project I’m working on. It allows you to define class-level defaults and still override instance definitions.
The implementation looks like this: