我有以下结构:
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
,而不必在我想使用时手动要求?
答案 0 :(得分: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'