Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inspection Warning: Cannot find declaration for field

Tags:

ruby

rubymine

Noob question. I ran RubyMine's Code Inspect on a file containing this class.

class Square
  attr_accessor :width

  def area
    @width * @width
  end
end

I was surprised to get two warnings on the line @width * @width:

Cannot find declaration for field '@width'

The attr section of the Style Guide wasn't helpful to me. Why is this a warning?

----Edit----
Ruby-Doc says this about attr-accessor

Defines a named attribute for this module, where the name is symbol.id2name, creating an instance variable (@name) and a corresponding access method to read it. Also creates a method called name= to set the attribute. String arguments are converted to symbols.

To me, "Defines" means it has a "declaration". The warning message doesn't make sense. "Warning: Field may not be initialized before use" is more accurate.

I think this is a RubyMine issue (if it is an issue at all). RubyMine apparently uses its own code inspection protocol and doesn't use a standard Linter.

like image 394
Mark Jerde Avatar asked Jun 10 '16 00:06

Mark Jerde


2 Answers

RubyMine's display of this warning in this situation is a known issue.

like image 153
Mark Jerde Avatar answered Oct 19 '22 07:10

Mark Jerde


It seems @width is not being initialized.

class Square
  attr_accessor :width

  def initialize(width)
    @width = width
  end

  def area
    @width * @width
  end
end

x = Square.new(4)
#=> #<Square:0x00000002371ef8 @width=4>
x.area
#=> 16

Without that you would get an error when calling Square.new.area (as the square has been defined without a width being set).

like image 35
Nabeel Avatar answered Oct 19 '22 06:10

Nabeel