Class: Rubocop::Cop::Style::StringLiterals

Inherits:
Cop
  • Object
show all
Defined in:
lib/rubocop/cop/style/string_literals.rb

Overview

Checks for uses of double quotes where single quotes would do.

Constant Summary collapse

MSG =
"Prefer single-quoted strings when you don't need " +
'string interpolation or special symbols.'

Instance Attribute Summary

Attributes inherited from Cop

#autocorrect, #corrections, #debug, #disabled_lines, #offences

Instance Method Summary collapse

Methods inherited from Cop

#add_offence, all, cop_name, cop_type, #do_autocorrect, #ignore_node, inherited, #initialize, lint?, #name, rails?, style?

Constructor Details

This class inherits a constructor from Rubocop::Cop::Cop

Instance Method Details

#autocorrect_action(node) ⇒ Object



30
31
32
33
34
35
# File 'lib/rubocop/cop/style/string_literals.rb', line 30

def autocorrect_action(node)
  @corrections << lambda do |corrector|
    corrector.replace(node.loc.begin, "'")
    corrector.replace(node.loc.end, "'")
  end
end

#on_str(node) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/rubocop/cop/style/string_literals.rb', line 11

def on_str(node)
  # Constants like __FILE__ are handled as strings,
  # but don't respond to begin.
  return unless node.loc.respond_to?(:begin)
  return if part_of_ignored_node?(node)

  # regex matches IF there is a ' or there is a \\ in the string that
  # is not preceeded/followed by another \\ (e.g. "\\x34") but not
  # "\\\\"
  if node.loc.expression.source !~ /' | (?<! \\) \\{2}* \\ (?! \\)/x &&
      node.loc.begin && node.loc.begin.is?('"')
    add_offence(:convention, node.loc.expression, MSG)
    do_autocorrect(node)
  end
end