10

I am trying to build a gem in Rails 3 and inside it i am trying to pass an initializer:

Credentials.configure do |config|
  file = File.read("#{Rails.root}/config/twitter.yaml")
  file_config = YAML.load(file)

  config.consumer_key = file_config[Rails.env][:consumer_key]
  config.consumer_secret = file_config[Rails.env][:consumer_secret]
  config.callback_url = URI.escape(file_config[Rails.env][:callback_url])
  config.time_stamp = Time.now.to_i
end

and then i am trying to call it like this:

Credentials.time_stamp

but i get this error:

uninitialized constant Twitter::Credentials

what is the problem?

Thanks

Wahtever
  • 3,597
  • 10
  • 44
  • 79

1 Answers1

15

Your gem will first need to define a generator in lib/generators/your_gem_name_generator.rb

mkdir -p lib/generators/

Copy your initializer in that folder with a name like twitter_credentials.rb

Then create another file in that folder with a name like twitter_generator.rb with content like this:

class YourGemNameRailtie < Rails::Generators::Base
  source_root(File.expand_path(File.dirname(__FILE__)))
  def copy_initializer
    copy_file 'twitter_credentials.rb', 'config/initializers/twitter_credentials.rb'
  end
end

You should check out the official documentation for creating a generator here: http://guides.rubyonrails.org/generators.html

Chris
  • 15,819
  • 3
  • 24
  • 37
Unixmonkey
  • 18,485
  • 7
  • 55
  • 78
  • But is there a way to keep a dynamic configuration file inside the gem itself? – Wahtever Apr 15 '13 at 11:21
  • @Wahtever Just `require` it? Re-reading the question, it seems your problem is there is no Credentials class. Have you implemented a Credentials class with a configure class method that accepts a block to hold state? – Unixmonkey Apr 15 '13 at 14:57