views:

86

answers:

2

In Ruby, I see that it can be useful to put classes inside modules for namespacing. I also see that it's possible to put moduldes inside classes. But I don't see why you'd do that.

Modules are generally mixed into classes, right? So what would be the purpose of defining a module inside a class?

(I also notice that Googling "ruby 'module inside a class'" gets 3 results, whereas "ruby 'class inside a module'" gets more than 18,000, so maybe the answer is "nobody does this"?)

+1  A: 

I guess it’s really just about using a class as a namespace, which is sometimes just more convenient that putting everything in a module. I’ve never seen that in practice, but it’s perfectly valid Ruby code either way.

The only real-life scenario I can think of is using EventMachine in a class:

class Api
  def initialize
    EM.start_server "0.0.0.0", 8080, Server
  end

  module Server
    def receive_data (data)
      # do stuff
    end
  end
end
Todd Yandell
+1  A: 
class Image
    module Colors
        Red = ...
        Blue = ...
    end
    include Colors
end

include Image::Colors

Image.new.set_pixel x, y, Red 
banister