class RuboCop::Cop::Lint::NestedMethodDefinition

This cop checks for nested method definitions.

@example

# bad

# `bar` definition actually produces methods in the same scope
# as the outer `foo` method. Furthermore, the `bar` method
# will be redefined every time `foo` is invoked.
def foo
  def bar
  end
end

@example

# good

def foo
  bar = -> { puts 'hello' }
  bar.call
end

@example

# good

def foo
  self.class_eval do
    def bar
    end
  end
end

def foo
  self.module_exec do
    def bar
    end
  end
end

@example

# good

def foo
  class << self
    def bar
    end
  end
end

Constants

MSG

Public Instance Methods

on_def(node) click to toggle source
# File lib/rubocop/cop/lint/nested_method_definition.rb, line 61
def on_def(node)
  find_nested_defs(node) do |nested_def_node|
    add_offense(nested_def_node)
  end
end
Also aliased as: on_defs
on_defs(node)
Alias for: on_def

Private Instance Methods

find_nested_defs(node) { |child| ... } click to toggle source
# File lib/rubocop/cop/lint/nested_method_definition.rb, line 70
def find_nested_defs(node, &block)
  node.each_child_node do |child|
    if child.def_type?
      yield child
    elsif child.defs_type?
      subject, = *child
      next if subject.lvar_type?
      yield child
    elsif !scoping_method_call?(child)
      find_nested_defs(child, &block)
    end
  end
end
scoping_method_call?(child) click to toggle source
# File lib/rubocop/cop/lint/nested_method_definition.rb, line 84
def scoping_method_call?(child)
  eval_call?(child) || exec_call?(child) || child.sclass_type? ||
    class_or_module_or_struct_new_call?(child)
end