加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 在编写宝石时设置配置设置

发布时间:2020-12-16 20:23:56 所属栏目:百科 来源:网络整理
导读:我正在编写一个我想要和没有Rails环境一起工作的宝石. 我有一个配置类允许配置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_acces
我正在编写一个我想要和没有Rails环境一起工作的宝石.

我有一个配置类允许配置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

现在可以这样使用:

NameChecker.configure do |config|
  config.api_key = 'dfskljkf'
end

但是,我似乎无法使用我的gem中的其他类访问我的配置变量.例如,当我在我的spec_helper.rb中配置gem时,如下所示:

# spec/spec_helper.rb
require "name_checker"

NameChecker.configure do |config|
  config.api_key = 'dfskljkf'
end

并从我的代码引用配置:

# lib/name_checker/net_checker.rb
module NameChecker
  class NetChecker
    p NameChecker.configuration.api_key
  end
end

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

`<class:NetChecker>': undefined method `api_key' for nil:NilClass (NoMethodError)

我的代码有什么问题?

解决方法

尝试重构:
def self.configuration
  @configuration ||=  Configuration.new
end

def self.configure
  yield(configuration) if block_given?
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读