Sha256: deed438b2a4313f971e4ac2b753ec88be23c82944b497819c30cfd5e6096efaa

Contents?: true

Size: 1.09 KB

Versions: 3

Compression:

Stored size: 1.09 KB

Contents

# encoding: utf-8

module Rubocop
  module Cop
    module Style
      # Checks for uses of double quotes where single quotes would do.
      class StringLiterals < Cop
        MSG = "Prefer single-quoted strings when you don't need " +
          'string interpolation or special symbols.'

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

          # 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 !~ /('|([^\\]|\A)\\([^\\]|\Z))/ &&
              node.loc.begin.is?('"')
            add_offence(:convention, node.loc.expression, MSG)
            do_autocorrect(node)
          end
        end

        alias_method :on_dstr, :ignore_node
        alias_method :on_regexp, :ignore_node

        def autocorrect_action(node)
          replace(node.loc.begin, "'")
          replace(node.loc.end, "'")
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 2 rubygems

Version Path
rubocop-0.9.1 lib/rubocop/cop/style/string_literals.rb
sabat-rubocop-0.9.0 lib/rubocop/cop/style/string_literals.rb
rubocop-0.9.0 lib/rubocop/cop/style/string_literals.rb