Fastest/One-liner way to list attr_accessors in Ruby?
Heres an alternative using a mixin rather than inheritance:
module TrackAttributes
def attr_readers
self.class.instance_variable_get('@attr_readers')
end
def attr_writers
self.class.instance_variable_get('@attr_writers')
end
def attr_accessors
self.class.instance_variable_get('@attr_accessors')
end
def self.included(klass)
klass.send :define_singleton_method, :attr_reader, ->(*params) do
@attr_readers ||= []
@attr_readers.concat params
super(*params)
end
klass.send :define_singleton_method, :attr_writer, ->(*params) do
@attr_writers ||= []
@attr_writers.concat params
super(*params)
end
klass.send :define_singleton_method, :attr_accessor, ->(*params) do
@attr_accessors ||= []
@attr_accessors.concat params
super(*params)
end
end
end
class MyClass
include TrackAttributes
attr_accessor :id, :title, :body
end
MyClass.new.attr_accessors #=> [:id, :title, :body]
Extract the attributes in to an array, assign them to a constant, then splat them in to attr_accessor
.
class SubClass < MyBaseClass
ATTRS = [:id, :title, :body]
attr_accessor(*ATTRS)
end
Now you can access them via the constant:
puts SubClass.ATTRS #=> [:id, :title, :body]
There is no way (one-liner or otherwise) to list all methods defined by attr_accessor and only methods defined by attr_accessor without defining your own attr_accessor.
Here's a solution that overrides attr_accessor in MyBaseClass to remember which methods have been created using attr_accessor:
class MyBaseClass
def self.attr_accessor(*vars)
@attributes ||= []
@attributes.concat vars
super(*vars)
end
def self.attributes
@attributes
end
def attributes
self.class.attributes
end
end
class SubClass < MyBaseClass
attr_accessor :id, :title, :body
end
SubClass.new.attributes.inspect #=> [:id, :title, :body]
Following up on Christian's response, but modifying to use ActiveSupport::Concern...
module TrackAttributes
extend ActiveSupport::Concern
included do
define_singleton_method(:attr_reader) do |*params|
@attr_readers ||= []
@attr_readers.concat params
super(*params)
end
define_singleton_method(:attr_writer) do |*params|
@attr_writers ||= []
@attr_writers.concat params
super(*params)
end
define_singleton_method(:attr_accessor) do |*params|
@attr_accessors ||= []
@attr_accessors.concat params
super(*params)
end
end
def attr_readers
self.class.instance_variable_get('@attr_readers')
end
def attr_writers
self.class.instance_variable_get('@attr_writers')
end
def attr_accessors
self.class.instance_variable_get('@attr_accessors')
end
end