简体   繁体   中英

Ruby Rails: How Rails handle same method name in in two different gems

Lets say i am using two gems namely 'A' and 'B' respectively . gem A defines module A as shown below.

module A
  def a
    puts "i am from module A"
  end
end

Gem B define module B as shown below

module B
  def a
    puts "i am from module B"
  end
end

Now i can include module B and A in class C.

class C
  include B
  include A
end

c = C.new
c.a  #i am from module A

Now both the modules defines method a . In real world there are lot of chances that method name defined in one gem will collide with method name of another gem. in such cases is it developers' responsibility to handle such situation or does Rails (Ruby) provide something which will take care of this situation?

You can avoid collisions or method stomping if you can anticipate which conflict you need to resolve. For example, two incomplatible modules:

module A
  def a
    :A
  end
end

module B
  def a
    :B
  end
end

These both implement the a method, which is going to conflict. If you need to use both you'll have to carefully import them, the onus is on your code:

class C
  # Import A
  include A

  # Create an alias for A's version of the a method called `A_a`
  alias_method :A_a, :a

  # Import B
  include B
end

C.new.a
# => :B
C.new.A_a
# => :A

Now they can co-exist instead of fighting like two angry cats.

Including a module simply makes that module the superclass of the class the module is included in.

So, include B makes B the superclass of C and the former superclass of C (ie Object ) the superclass of B . Then, include A makes A the superclass of C and the former superclass of C (ie B ) the superclass of A .

Therefore, A#a simply overrides B#a . There is nothing special about it. It's just boring old class inheritance and method overriding.

To answer your question directly: This is ultimately the responsibility of the developer who uses the gems. The authors of gems should take some care to name their methods appropriately, but nothing they can (or should) do will obviate the possibility of a collision.

This feature of Ruby is very powerful, but as always, with great power comes great potential for disaster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM