Add Ruby classes to a module when defined in separ

2019-07-14 21:17发布

问题:

I would like to namespace my Ruby classes by putting them in a module. Indeed, this is a good idea if I decide to publish my Ruby gem so that the class names do not clash with existing classes in another gem. I know I can do the following for a class A::B:

module A
  class B

  end
end

However, the above is quite cumbersome in that I need to put all my class definitions into a single Ruby source file in order to scope them under the module. I would rather keep my class definitions in separate source files, much like a Java project, so how can I add classes to a module when they are all defined in separate files?

回答1:

The accepted practice in this case is to wrap every file in module block

# a/b.rb
module A
  class B

  end
end

# a/c.rb
module A
  class C

  end
end

Btw. because of the way constant are resolved, it is advisable to use the long form I quoted above instead class A::B

(http://blog.honeybadger.io/avoid-these-traps-when-nesting-ruby-modules/).