Victor Pudeyev
Victor Pudeyev

Reputation: 4538

How to make a ruby gem read an initializer?

I am writing a gem for ruby on rails that depends on an initializer. I have config/initializers/pi.rb with:

PI_KEY = 'my key'
PI_SECRET = 'my secret'

and in the gem's lib/pi.rb I'd like to have:

module Pi
  HEADERS = {
    'X-Auth-Key' => ::PI_KEY
    'X-Auth-Secret' => ::PI_SECRET
  }
end

but PI_KEY is undefined at the time the gem loads. Rails.root is also undefined at that time, so I can't just require the initializer. So how would I pass config to my gem from a rails initializer?

Upvotes: 0

Views: 891

Answers (1)

Julien
Julien

Reputation: 2329

You could do it like this for example:

in your lib/pi.rb:

module Pi
  class << self
    mattr_accessor :key, :secret
  end

  def self.configure(&block)
    yield self
  end
end

then in the application's config/initializers/pi.rb:

Pi.configure do |config|
  config.key = 'some key'
  config.secret = 'I am Batman'
end

Upvotes: 3

Related Questions