views:

107

answers:

2
module Superpower

    # instance method
    def turn_invisible
     ...
    end

    # module method
    def Superpower.turn_into_toad
     ...
    end

    module Fly
     def flap_wings
      ...
     end
    end

end

Class Superman
    include Superpower
    ...

    def run_away
     # how to call flap_wings?
     # how to call turn_invisible?
    end

    def see_bad_guys(bad_guy = lex_luthor)
        #is this correct?
        Superpower.turn_into_toad(bad_guy)
    end
end

Hi I saw some ruby code which I couldn't understand. How do you call flap_wings from within the Superman class? Is it possible to call an instance method from within the class? What is the difference between including modules and embedding modules? Why and when should you do that?

+1  A: 

You want to read the documentation on mixins which are a way to workaround the fact that Ruby has only single inheritance. By including a given module A in a class B, all the modules methods in A are available as if they were actually part of class B.

That means that calling turn_invisible is as easy as

def run_away
  turn_invisible
end

For flap_wings as it is in another namespace, it may be as easy as:

def fly_away
  Fly.flap_wings
end

but I haven't not tried to complete your code and "run" it.

Mixins are explained here and there.

Keltia
+1  A: 

I'm assuming that when you say embedding a module you mean the "Fly" module from your example is embedded in "Superpower".

If that is the case, I would call it a nested module. The only time I would use a Nested Module is when the nested module deals specifically with the main module, such that the code in Fly is directly correlated to Superpower, but are separated for convenience and readability.

You can use the nested module's methods simply by including superpower first, then fly second, like so:

Class Superman
    include Superpower
    include Fly
    # ...
end

The details are described further on this blog.

localshred