I have a folder structure like the following in one of my projects:
- lib
- bar.rb
- bar
- other_bar.rb
- another_bar.rb
- next_bar.rb
- …
bar.rb
require File.expand_path(File.dirname(__FILE__) + "/bar/other_bar.rb")
class Bar
puts "running BarBase"
end
bar/other_bar.rb
module Bar
class OtherBar
puts "running module Bar with class OtherBar"
end
end
If I now run ruby bar.rb I get this:
running module Bar with class OtherBar
bar.rb:3:in `’: Bar is not a class (TypeError)
I’d like to have a similar structure to a rails model inheritance structure. How can I fix this? So far as I know ruby does not support this out of the box. Is there a workaround for such a situation?
Barcan’t be a module and a class, they are different things.Change
bar.rbtomodule Baror changeother_bar.rbtoclass Bar.Whichever it is, it has to be consistent. You can’t change one to the other. The question is which should it be? If
Baris a container for other classes and only has a few global singleton methods? Then it’s amodule. But if it can be instantiated, then it’s aclass.And yes, you can nest classes. This is totally acceptable:
Modules and Classes can be nested inside either other in any way you see fit.
Edit with some commented examples to help clear this all up: