编写gem时设置配置设置

Dav*_*ite 14 ruby rubygems

我正在写一个我想要使用的宝石,没有Rails环境.

我有一个Configuration类允许配置gem:

module NameChecker
  class Configuration
    attr_accessor :api_key, :log_level

    def initialize
      self.api_key = nil
      self.log_level = 'info'
    end
  end

  class << self
    attr_accessor :configuration
  end

  def self.configure
    self.configuration ||= Configuration.new
    yield(configuration) if block_given?
  end
end
Run Code Online (Sandbox Code Playgroud)

现在可以这样使用:

NameChecker.configure do |config|
  config.api_key = 'dfskljkf'
end
Run Code Online (Sandbox Code Playgroud)

但是,我似乎无法从我的gem中的其他类访问我的配置变量.例如,当我在我spec_helper.rb这样配置gem时:

# spec/spec_helper.rb
require "name_checker"

NameChecker.configure do |config|
  config.api_key = 'dfskljkf'
end
Run Code Online (Sandbox Code Playgroud)

并从我的代码中引用配置:

# lib/name_checker/net_checker.rb
module NameChecker
  class NetChecker
    p NameChecker.configuration.api_key
  end
end
Run Code Online (Sandbox Code Playgroud)

我得到一个未定义的方法错误:

`<class:NetChecker>': undefined method `api_key' for nil:NilClass (NoMethodError)
Run Code Online (Sandbox Code Playgroud)

我的代码出了什么问题?

小智 18

尝试重构:

def self.configuration
  @configuration ||=  Configuration.new
end

def self.configure
  yield(configuration) if block_given?
end
Run Code Online (Sandbox Code Playgroud)