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

Inherits:
Cop
  • Object
show all
Includes:
StringHelp
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.'

Constants inherited from Cop

Cop::OPERATOR_METHODS

Instance Attribute Summary

Attributes inherited from Cop

#config, #corrections, #offences, #processed_source

Instance Method Summary collapse

Methods included from StringHelp

#on_dstr, #on_regexp, #on_str

Methods inherited from Cop

#add_offence, all, #autocorrect?, #convention, #cop_config, cop_name, #cop_name, cop_type, #debug?, #ignore_node, inherited, #initialize, lint?, #message, rails?, style?, #warning

Constructor Details

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

Instance Method Details

#autocorrect_action(node) ⇒ Object



21
22
23
24
25
26
# File 'lib/rubocop/cop/style/string_literals.rb', line 21

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

#offence?(node) ⇒ Boolean

Returns:

  • (Boolean)


13
14
15
16
17
18
19
# File 'lib/rubocop/cop/style/string_literals.rb', line 13

def offence?(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
  # "\\\\"
  node.loc.expression.source !~ /' | (?<! \\) \\{2}* \\ (?! \\)/x &&
    node.loc.begin && node.loc.begin.is?('"')
end