class RuboCop::Cop::Lint::PercentStringArray
rather than meant to be part of the resulting strings.
example, mistranslating an array of literals to percent string notation)
it is more likely that the additional characters are unintended (for
`%w(‘foo’, “bar”)‘
This cop checks for quotes and commas in %w, e.g.
def autocorrect(node)
def autocorrect(node) lambda do |corrector| node.children.each do |child| range = child.loc.expression match = /['"]?,?$/.match(range.source) corrector.remove_trailing(range, match[0].length) if match corrector.remove_leading(range, 1) if /^['"]/ =~ range.source end end end
def contains_quotes_or_commas?(node)
def contains_quotes_or_commas?(node) patterns = [/,$/, /^'.*'$/, /^".*"$/] node.children.any? do |child| literal = child.children.first # To avoid likely false positives (e.g. a single ' or ") next if literal.to_s.gsub(/[^\p{Alnum}]/, '').empty? patterns.any? { |pat| literal =~ pat } end end
def on_array(node)
def on_array(node) process(node, *%w(%w %W)) end
def on_percent_literal(node)
def on_percent_literal(node) if contains_quotes_or_commas?(node) add_offense(node, :expression, MSG) end end