0

I am having some struggle using rubocop and don't know how I could solve this problem.

The code I have:

class Test
  @hello = 'stackoverflow'

  def self.hello
    @hello
  end
end

p Test.hello

It runs the way i want, but when I run rubocop it says to use attr_reader. If I try to use attr_reader it gives me NoMethodError.

I already tried to solve this like this, but rubocop is still not happy.

class Test2
  @hello = 'stackoverflow'

  class << self
    def hello
      @hello
    end
  end
end

How could I solve this?

Domas Mar
  • 1,148
  • 1
  • 11
  • 23

1 Answers1

2

You need to use attr_reader on singleton class so it adds "hello" method to your Test singleton class.

class Test
  @hello = 'stackoverflow'

  class << self
    attr_reader :hello
  end
end
Pavel S
  • 389
  • 1
  • 9
  • Thank you it seems to work fine. But I got a new problem, that my method and field names are different. – Domas Mar Oct 26 '14 at 13:35
  • if your method and instance variable names are different rubocop should not complain with your initial implementation. – Pavel S Oct 26 '14 at 13:37