Mulan
Mulan

Reputation: 135197

How to inherit module methods in a class in Ruby?

Off the bat, this feels like a dumb question... but I feel like I missing something here

How do I automatically inherit module methods in a class that belongs to a module?

module MyModule

  def hello
    puts "hello"
  end

  class Foo; end
  class Bar; end
end

Halp

f = MyModule::Foo.new
f.hello
# NoMethodError: undefined method `hello' for #<MyModule::Foo:0x007f8d8b010200>

b = MyModule::Bar.new
b.hello
# NoMethodError: undefined method `hello' for #<MyModule::Bar:0x007f8d8b03a140>

I feel like I shouldn't have to do this

module MyModule
  class Foo
    include MyModule
  end
end

Otherwise what's the point of putting the class in the module?

Upvotes: 0

Views: 414

Answers (1)

Paulo Bu
Paulo Bu

Reputation: 29794

I don't understand quite well what are you trying to accomplish doing that. As far as I'm concern, Modules in Ruby are used as namespaces and mixins.

How do you expect that all classes inside a module contain the module functions defined before? For me, that doesn't make sense. Probably, you're trying to force that behavior which is not a feature in Ruby.

Normally, you'll be compliant with languages constraints, create a module, functions inside them which share some common objective, and later include them inside a class to extend its behavior --another way to circumvent the lack of multiple inheritance.

I don't see the beauty of what you're trying to accomplish. As I said, modules are used as namespaces and mixin, other than that, is not what Ruby's community intended for them.

About the point of putting a class in a module, I guess is no other than modularity and object oriented programming practices.

Upvotes: 1

Related Questions