Sha256: 84cc9c6dfb8be5e68387f9a2dea53bb15ea6f14d99f875880c2be8df8f22885a

Contents?: true

Size: 1.39 KB

Versions: 3

Compression:

Stored size: 1.39 KB

Contents

# encoding: utf-8

module Rubocop
  module Cop
    module Style
      # Checks if uses of quotes match the configured preference.
      class StringLiterals < Cop
        include ConfigurableEnforcedStyle
        include StringHelp

        private

        def message(node)
          if style == :single_quotes
            "Prefer single-quoted strings when you don't need string " \
            'interpolation or special symbols.'
          else
            'Prefer double-quoted strings unless you need single quotes to ' \
            'avoid extra backslashes for escaping.'
          end
        end

        def offence?(node)
          src = node.loc.expression.source
          return false if src =~ /^(%[qQ]?|\?|<<-)/i
          src !~ if style == :single_quotes
                   # 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 "\\\\"
                   /' | (?<! \\) \\{2}* \\ (?! \\)/x
                 else
                   /" | \\/x
                 end
        end

        def autocorrect(node)
          @corrections << lambda do |corrector|
            replacement = node.loc.begin.is?('"') ? "'" : '"'
            corrector.replace(node.loc.begin, replacement)
            corrector.replace(node.loc.end, replacement)
          end
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
rubocop-0.18.1 lib/rubocop/cop/style/string_literals.rb
rubocop-0.18.0 lib/rubocop/cop/style/string_literals.rb
rubocop-0.17.0 lib/rubocop/cop/style/string_literals.rb