简体   繁体   中英

Ruby excetend multiple class inside Module

Hello someone can help me? I need to extend multiple class inside one module, i try in this way but not work.

module A
  def hello_A
    puts "hello from module A"
  end

end

module B
  extend A
  class C
    extend A
    def self.hello_B_C
      puts "Hello from Module B => Class C"
    end
  end

  class D
    def self.hello_B_D
      puts "Hello from Module B => Class D"
    end
  end
end

B::C.hello_B_C  => #Hello from Module B => Class C 
B::C.hello_A    => #Hello from module A
B::D.hello_A    => #undefined method `hello_A' for B::D:Class

I whold extend module A in Module B, and use hello_A in all subclass of Module B

B::D.hello_A wouldn't work.

when you have this:

class B
  extend A
  class D
  end
end

The class D does not share any functionality with B. B::D is nothing but a namespace .

If you instead did

class B
  extend A
  class D < self
  end
end

Now D inherits all the behavior from B.

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