square/cane

value "class" raises exception in multiline definition of array using %w

wteuber opened this issue · 3 comments

The value "class" raises exception in a multi-line definition of an array using %w.

HTML_ATTRS = %w[
  class
  style
  ...
]

raises undefined method `[]' for nil:NilClass (NoMethodError) in line

line.match(/class\s+([^\s;]+)/)[1]

In method find_violations the condition

class_definition?(line) && !comment?(last_line)

is not specific enough. Something like

class_definition?(line) && !comment?(last_line) && !array_context?

would be great.

A workaround is, to make non-class-definition-lines not match

/^\s*class\s+/

For the example above, this means:

HTML_ATTRS = %w[ class
  style
  ...
]

Thanks! Looks like you've already figured out the solution, want to put together a PR?

Unfortunately I haven't figured out a solution (yet), just a work-around. If I got some spear time, I will try to to fix the issue instead of just avoiding it.

We don't know if we're in an array context, because this check uses grep rather than source parsing for speed. I tightened up the regex used for classes which fixes your specific issue.