如果文件相互依赖,如何在 ruby gem 中要求文件

how to require files in a ruby gem if they depend on each other

我有以下结构:

lib/billomat.rb

require 'dry-configurable'
require 'httparty'

require 'billomat/version'
require 'billomat/account'

module Billomat
  extend Dry::Configurable

  setting :subdomain
  setting :api_key
end

lib/billomat/base.rb

class Billomat::Base
  include HTTParty
  base_uri "https://#{Billomat.config.subdomain}.billomat.net/api"

  def initialize
    @options = { format: 'json', headers: {
      'X-BillomatApiKey' => Billomat.config.api_key
    } }
  end
end

lib/billomat/account.rb

require_relative 'base'

class Billomat::Account < Billomat::Base
  def info
    puts Billomat.config.subdomain
    self.class.get('/clients/myself', @options)
  end
end

如果我尝试使用 bin/console 访问控制台,我会收到错误消息:

lib/billomat/base.rb:3:in `<class:Base>': undefined method `config' for Billomat:Module (NoMethodError)

gem 尝试加载依赖于 base.rb 的 account.rb,而 base.rb 使用 Billomat.config,此时它还没有准备好。我尝试从 billomat.rb 中删除 require 'billomat/account' 并再次打开控制台。现在,我实际上可以实例化 Billomat.config,但我尝试调用 Billomat::Account.new.info 我得到另一个错误:

irb(main):005:0> Billomat::Account
NameError: uninitialized constant Billomat::Account

因为此时当然不需要 billomat/account,所以我必须手动要求。

问题是:我如何组织代码,这样我就可以调用 Billomat.configuire {} 然后调用 Billomat::Account.new.info 而无需在我想使用时手动要求它?

Ruby 是一种脚本语言,它逐行读取和处理。只需更改顺序:

lib/billomat.rb

require 'dry-configurable'
require 'httparty'

module Billomat
  extend Dry::Configurable

  setting :subdomain
  setting :api_key
end

require 'billomat/version'
require 'billomat/account'