Sha256: f16d6be7e6a483f43ed751b263bd705eaf10475e3f430bdc4e364cf349497e64

Contents?: true

Size: 1.9 KB

Versions: 5

Compression:

Stored size: 1.9 KB

Contents

# encoding: utf-8

module RuboCop
  module Cop
    module Style
      # This cop checks for whitespace within string interpolations.
      #
      # @example
      #   # Good if EnforcedStyle is no_space, bad if space.
      #      var = "This is the #{no_space} example"
      #
      #   # Good if EnforceStyle is space, bad if no_space.
      #      var = "This is the #{ space } example"
      class SpaceInsideStringInterpolation < Cop
        include ConfigurableEnforcedStyle

        NO_SPACE_MSG = 'Space inside string interpolation detected.'
        SPACE_MSG = 'Missing space around string interpolation detected.'

        def on_dstr(node)
          node.children.select { |n| n.type == :begin }.each do |begin_node|
            final_node = begin_node.children.last
            next unless final_node

            interp = final_node.loc.expression
            interp_with_surrounding_space = range_with_surrounding_space(interp)
            if style == :no_space
              if interp_with_surrounding_space != interp
                add_offense(final_node, :expression, NO_SPACE_MSG)
              end
            elsif style == :space
              if interp_with_surrounding_space.source != " #{interp.source} "
                add_offense(final_node, :expression, SPACE_MSG)
              end
            end
          end
        end

        private

        def autocorrect(node)
          if style == :no_space
            lambda do |corrector|
              corrector.replace(
                range_with_surrounding_space(node.loc.expression),
                node.loc.expression.source
              )
            end
          elsif style == :space
            lambda do |corrector|
              corrector.replace(
                range_with_surrounding_space(node.loc.expression),
                " #{node.loc.expression.source} "
              )
            end
          end
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
rubocop-0.35.1 lib/rubocop/cop/style/space_inside_string_interpolation.rb
rubocop-0.35.0 lib/rubocop/cop/style/space_inside_string_interpolation.rb
rubocop-0.34.2 lib/rubocop/cop/style/space_inside_string_interpolation.rb
rubocop-0.34.1 lib/rubocop/cop/style/space_inside_string_interpolation.rb
rubocop-0.34.0 lib/rubocop/cop/style/space_inside_string_interpolation.rb