Add Ruby classes to a module when defined in separ

2019-07-14 20:58发布

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条回答
\"骚年 ilove
2楼-- · 2019-07-14 21:40

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/).

查看更多
登录 后发表回答