How do you make all attributes public in ruby class -
i have class 20+ attributes, want each of them publicly readable or if not public.
i cannot seem find data relevant this. can me here please?
i want make of them public without having type 20+ attributes attr_reader.
you can using method_missing
. method_missing
called whenever tries call method class doesn't know how respond to.
class foo def initialize @a = 1 @b = 2 @c = 3 end def respond_to_missing?(name) super || has_attribute?(name) end def method_missing(name, *args) if has_attribute?(name) instance_variable_get("@#{name}") else super end end private def has_attribute?(name) instance_variable_defined?("@#{name}") end end
here's looks when use it
foo = foo.new p foo.a # => 1 p foo.b # => 2 p foo.c # => 3 p foo.d # => method_missing error
note: ruby earlier 1.9.2: override respond_to?
instead of respond_to_missing?
Comments
Post a Comment