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?
The gem command allows you to interact with RubyGems. Ruby 1.9 and newer ships with RubyGems built-in but you may need to upgrade for bug fixes or new features. To upgrade RubyGems, visit the download page. If you want to see how to require files from a gem, skip ahead to What is a gem. Finding Gems.
development. RubyGems provides two main “types” of dependencies: runtime and development. Runtime dependencies are what your gem needs to work (such as rails needing activesupport). Development dependencies are useful for when someone wants to make modifications to your gem.
Try refactoring to:
def self.configuration
@configuration ||= Configuration.new
end
def self.configure
yield(configuration) if block_given?
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With