Call method in a nested module included in a class

I have the following configuration:

module A module B def foo puts "foo" end end end class C include A end c = C.new c.foo NoMethodError: undefined method `foo' for #<C:0x8765284> 

How to achieve the above?

Thanks.

+4
source share
2 answers

Module B is β€œdefined” inside A, it is not β€œincluded” in A. That's why you do not get access to the instance method #foo when you turn module A on C. You can do the following:

 class C include A::B end C.new.foo 
+5
source

You can use the included callback to enable B when A enabled.

 module A def A.included(klass) klass.include B end module B def foo puts "foo" end end end class C include A end 

and the following will work

 c = C.new c.foo 
0
source

Source: https://habr.com/ru/post/1393278/


All Articles