shikhar.ja shikhar.ja - 4 years ago 79
Ruby Question

How do you make all attributes public in ruby class

I have a class with 20+ attributes, I want each of them to be publicly readable or if not that then public.

I cannot seem to find any data relevant to this. Can anyone help me here please?

I want to make all of them public without having to type all 20+ attributes with attr_reader.

Answer Source

You can do this using method_missing. method_missing is called whenever someone tries to call a method that your class doesn't know how to 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 what it looks like when you use it

foo = Foo.new
p foo.a    # => 1
p foo.b    # => 2
p foo.c    # => 3
p foo.d    # => method_missing error

Note: For Ruby earlier than 1.9.2: Override respond_to? instead of respond_to_missing?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download