如果彼此依赖,如何要求ruby gem中的文件

问题描述 投票:0回答:1

我有以下结构:

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试图加载依赖于使用Billomat.config的base.rb的account.rb,在此它没有准备好。我尝试从require 'billomat/account'删除billomat.rb并再次打开控制台。现在,我实际上可以实例化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 rubygems
1个回答
0
投票

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'
© www.soinside.com 2019 - 2024. All rights reserved.