Sha256: c6fd69ff004a2d7e9d80d1bfabaddff29dc38ab80b24e85433e5fda3244d4a75

Contents?: true

Size: 1 KB

Versions: 9

Compression:

Stored size: 1 KB

Contents

# encoding: utf-8

module RuboCop
  module Cop
    module Style
      # This cop checks for variable interpolation (like "#@ivar").
      class VariableInterpolation < Cop
        MSG = 'Replace interpolated variable `%s` with expression `#{%s}`.'

        def on_dstr(node)
          check_for_interpolation(node)
        end

        def on_regexp(node)
          check_for_interpolation(node)
        end

        def on_xstr(node)
          check_for_interpolation(node)
        end

        private

        def check_for_interpolation(node)
          var_nodes(node.children).each do |v|
            var = v.loc.expression.source

            add_offense(v, :expression, format(MSG, var, var))
          end
        end

        def autocorrect(node)
          expr = node.loc.expression
          ->(corrector) { corrector.replace(expr, "{#{expr.source}}") }
        end

        def var_nodes(nodes)
          nodes.select { |n| [:ivar, :cvar, :gvar, :nth_ref].include?(n.type) }
        end
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
rubocop-0.35.1 lib/rubocop/cop/style/variable_interpolation.rb
rubocop-0.35.0 lib/rubocop/cop/style/variable_interpolation.rb
rubocop-0.34.2 lib/rubocop/cop/style/variable_interpolation.rb
rubocop-0.34.1 lib/rubocop/cop/style/variable_interpolation.rb
rubocop-0.34.0 lib/rubocop/cop/style/variable_interpolation.rb
rubocop-0.33.0 lib/rubocop/cop/style/variable_interpolation.rb
rubocop-0.32.1 lib/rubocop/cop/style/variable_interpolation.rb
rubocop-0.32.0 lib/rubocop/cop/style/variable_interpolation.rb
rubocop-0.31.0 lib/rubocop/cop/style/variable_interpolation.rb