【问题标题】:Organize a structure of gem组织 gem 的结构
【发布时间】:2014-08-13 18:45:44
【问题描述】:

我编写 gem,它是对 faker gem 的补充(具有俄罗斯功能,如 tax & vat 等)

所以,我有一个麻烦:每段代码都很大,所以我需要将其拆分为逻辑部分。

IE 我有Inn 功能被称为Faker::Russian.inn()

所以,我写

Dir['faker/russian/*.rb'].each { |file| require file }

module Faker
  class Russian
    extend Inn
  end
end

否则我有(faker/russian/inn.rb)(这是必需的)这个文件

module Inn
  def inn ; puts 'inn goes here' ; end
end

但我有一个错误:lib/faker/russian.rb:5:in <class:Russian>': uninitialized constant Faker::Russian::Inn (NameError)

如何避免此错误并成功自动包含代码和extend 所有连接的模块?

【问题讨论】:

    标签: ruby gem metaprogramming faker


    【解决方案1】:

    选项1是在扩展时引用顶级命名空间

    extend ::Inn
    

    选项 2 是用正确的命名空间定义 Inn

    module Faker
      module Russian
        module Inn
          def inn; end
        end
      end
    end
    

    在 gem 选项 2 中,最好将所有模块命名在此 gem 的顶级模块下。想象一下,如果您使用选项 1 并且在应用程序中有一个 Inn 模块但没有 gem,您会遇到问题。

    【讨论】:

    • 我使用第二种方式仍然得到这个:<class:Russian>': uninitialized constant Faker::Russian::Inn (NameError)
    • 第一种方式也行不通。我得到<class:Russian>': uninitialized constant Inn (NameError)。也许我不太需要文件?
    • 我明白了。 #2 中存在名称冲突。该模块被命名为“Russian”,而类名也是“Russian”。给他们合适的名字,他们应该没问题。
    猜你喜欢
    • 2016-06-15
    • 1970-01-01
    • 2023-04-01
    • 2015-12-16
    • 2019-02-27
    • 2018-12-30
    • 1970-01-01
    • 2011-04-16
    相关资源
    最近更新 更多