Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting up configuration settings when writing a gem

Tags:

ruby

rubygems

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?

like image 780
David Tuite Avatar asked May 14 '12 13:05

David Tuite


People also ask

What is gem command?

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.

What is gem dependency?

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.


1 Answers

Try refactoring to:

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

def self.configure
  yield(configuration) if block_given?
end
like image 188
Arbind Thakur Avatar answered Oct 14 '22 10:10

Arbind Thakur