Add Ruby classes to a module when defined in separate files

£可爱£侵袭症+ 提交于 2019-12-11 03:07:10

问题


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



来源:https://stackoverflow.com/questions/49197182/add-ruby-classes-to-a-module-when-defined-in-separate-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!