ruby / did_you_mean

The gem that has been saving people from typos since 2014

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Calling Class Method suggests instance method

octosteve opened this issue · comments

I'm working on refining this issue, but replicating was a pain. Here's the code I wrote that triggered the 'did_you_mean' error. Take a look at the define_multi method. That code is probably what does it. My guess is since the lambda wraps a class method Method Object, then calls it when in an instance method, what you use for a look up gets confused.

require 'pry'
module DefineMulti
  def method_added(the_method)
    @overloaded_methods ||= Hash.new{|k,v| k[v] = []}
    return if @overloaded_methods.values.flatten.include?(the_method)
    # return if @overloaded_methods[the_method]

    method_obj = instance_method(the_method)
    arity = method_obj.arity
    new_method_name = "_#{arity}_#{the_method}".to_sym
    @overloaded_methods[the_method] << new_method_name
    alias_method new_method_name, the_method
  end

  def define_multi(&block)
    method_added = class_eval(&block)
    loaded_method = ->(args) {method(:dispatch).call(method_added, *args)}
    class_eval do
      define_method method_added, &loaded_method
    end
  end

  def dispatch(original_caller, *args)
    binding.pry
    puts "Called"
  end
end

class MultiClass
  extend DefineMulti
  define_multi do
    def multiple_heads(arg)
      puts "One Arg"
    end

    def multiple_heads(arg1, arg2)
      puts "Two Args"
    end
  end
end

MultiClass.new.multiple_heads("beef")