编写宝石时设置配置设置 [英] Setting up configuration settings when writing a gem

查看:88
本文介绍了编写宝石时设置配置设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个配置

c $ c> class允许配置gem:

  module NameChecker 
class配置
attr_accessor: api_key,::log_level

def初始化
self.api_key = nil
self.log_level ='info'
end
end

class<< self
attr_accessor:configuration
end
$ b def self.configure
self.configuration || = Configuration.new
如果block_given是yield(配置)?
end
end

现在可以这样使用:

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

但是, t似乎能够访问我的配置变量与其他类在我的宝石。例如,当我在 spec_helper.rb 中配置gem时,像这样:

 #spec / spec_helper.rb 
需要name_checker

NameChecker.configure do | config |
config.api_key ='dfskljkf'
结束

并参考配置我的代码:

 #LIB / name_checker / net_checker.rb 
模块NameChecker
类NetChecker
p NameChecker.configuration.api_key
end
end

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

 `<类:NetChecker> ':未定义的方法`API_KEY' 的零:NilClass(NoMethodError)$ b $ 

解决方案

尝试重构:

  def self.configuration 
@configuration || =配置.new
end

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


I'm writing a gem which I would like to work with and without the Rails environment.

I have a Configuration class to allow configuration of the 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

This can now be used like so:

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

However, I don't seem to be able to access my configuration variables from withing the other classes in my gem. For example, when I configure the gem in my spec_helper.rb like so:

# spec/spec_helper.rb
require "name_checker"

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

and reference the configuration from my code:

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

I get an undefined method error:

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

What is wrong with my code?

解决方案

Try refactoring to:

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

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

这篇关于编写宝石时设置配置设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆