rubyrubocop

How to define a Ruby method in runtime so that Rubocop doesn't complain?


I'm doing this:

class F
  def foo
    @x = Object.new
    def @x.bar(_t)
      true
    end
  end
end

Rubocop complains:

a.rb:4:5: W: Lint/NestedMethodDefinition: Method definitions must not be nested. Use lambda instead.
    def @x.bar(_t) ...
    ^^^^^^^^^^^^^^

I can't understand how to refactor this code to make Rubocop happy.


Solution

  • Rubocop sees this as a nested method definition although it isn't. (I think this is because of the @, you might want to report this as an issue).

    To make Rubocop "happy", you could just ignore that specific cop:

    def foo
      @x = Object.new
      def @x.bar(_t) # rubocop:disable Lint/NestedMethodDefinition
        true
      end
    end
    

    Alternatively, you could define the method in other "good" ways:

    class << @x
      def bar(_t)
        true
      end
    end
    
    @x.instance_eval do
      def bar(_t)
        true
      end
    end
    
    @x.define_singleton_method(:bar) do |_t|
      true
    end