Today I Learned

hashrocket A Hashrocket project

Accessors For All

Today I learned that accessors like attr_reader work in the private and protected visibilities.

class Test
  def initialize(getter, reader)
    @getter = getter
    @reader = reader
  end

  private

  def getter
    @getter
  end

  attr_reader :reader
end
2.2.3 :001 > t = Test.new('foo', 'bar')
 => #<Test:0x007f8f9b259bf8 @getter="foo", @reader="bar">
2.2.3 :002 > t.send(:getter)
 => "foo"
2.2.3 :003 > t.send(:reader)
 => "bar"

This can produce warnings in tests, discussed here:

https://bugs.ruby-lang.org/issues/10967

My current feeling is that these methods are a Ruby convention and should be used whenever appropriate, despite warnings in test.

See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.