问题描述
我正在尝试在Rails 3中构建一个gem,并且它正在尝试传递一个初始化程序:
凭证。配置do | config |
file = File.read(#{Rails.root} /config/twitter.yaml)
file_config = YAML.load(文件)
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
然后我我想这样调用它:
Credentials.time_stamp
但我得到这个错误:
未初始化的常量Twitter :: Credentials
有什么问题?
谢谢
mkdir -p lib / generators /
使用名称 twi将名称初始化程序复制到该文件夹中tter_credentials.rb
然后在该文件夹中创建另一个文件,名称如 twitter_generator.rb $ c $这样的内容:
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
您应该查看创建生成器的官方文档这里:
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
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
这篇关于Rails如何在宝石内创建初始化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!