Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work through name collisions in ruby

Two modules Foo and Baa respectively define a method with the same name name, and I did include Foo and include Baa in a particular context.

When I call name, how can I disambiguate whether to call the name method of Foo or Baa?

like image 277
american-ninja-warrior Avatar asked Sep 24 '18 18:09

american-ninja-warrior


1 Answers

Only the order of modules inclusion decides which one will get called. Can't have both with the same name - the latter will override the former.

Of course, you can do any tricks, just from the top of my head:

module A
  def foo
    :foo_from_A
  end
end

module B
  def foo
    :foo_from_B
  end
end

class C
  def initialize(from)
    @from = from
  end

  def foo
    from.instance_method(__method__).bind(self).call
  end

  private

  attr_reader :from
end

C.new(A).foo #=> :a_from_A
C.new(B).foo #=> :a_from_B

But that's no good for real life use cases :)

like image 155
Andrey Deineko Avatar answered Nov 15 '22 05:11

Andrey Deineko