Rails環境の有無にかかわらず作業したいgemを書いています。
私はConfiguration
宝石の設定を許可するクラスを持っています:
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
ようになります。
# 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)
コードの何が問題になっていますか?