Class: RuboCop::Cop::Rails::HelperInstanceVariable

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/rails/helper_instance_variable.rb

Overview

Checks for use of the helper methods which reference instance variables.

Relying on instance variables makes it difficult to reuse helper methods.

If it seems awkward to explicitly pass in each dependent variable, consider moving the behavior elsewhere, for example to a model, decorator or presenter.

Provided that an instance variable belongs to a class, an offense will not be registered.

Examples:

# bad
def welcome_message
  "Hello #{@user.name}"
end

# good
def welcome_message(user)
  "Hello #{user.name}"
end

# good
module ButtonHelper
  class Welcome
    def initialize(text:)
      @text = text
    end
  end

  def welcome(**)
    render Welcome.new(**)
  end
end

Constant Summary collapse

MSG =
'Do not use instance variables in helpers.'

Instance Method Summary collapse

Instance Method Details

#on_ivar(node) ⇒ Object



46
47
48
49
50
# File 'lib/rubocop/cop/rails/helper_instance_variable.rb', line 46

def on_ivar(node)
  return if instance_variable_belongs_to_class?(node)

  add_offense(node)
end

#on_ivasgn(node) ⇒ Object



52
53
54
55
56
# File 'lib/rubocop/cop/rails/helper_instance_variable.rb', line 52

def on_ivasgn(node)
  return if node.parent.or_asgn_type? || instance_variable_belongs_to_class?(node)

  add_offense(node.loc.name)
end