How do I get the Rails application name within a rake task?
I'm trying to write a Rails 3 rake
task to generate config/initializers/secret_token.rb
. I want to pull the application's name instead of hard-coding it in the rake task, but @app_name
is not yet populated, nor is ENV['APP_NA开发者_运维问答ME']
. Here's the task's code:
desc "Regenerate the server secret"
task :generate_secret do
include ActiveSupport
File.open('config/initializers/secret_token.rb', 'w') do |f|
f.puts "#{@app_name}::Application.config.secret_token = '#{SecureRandom.hex(30)}'"
end
end
It all works except that @app_name
is blank. How can I retrieve the application name here?
You need to use the environment in the rake task. Then you can use Rails.application.class.parent_name
desc "Regenerate the server secret"
task :generate_secret => :environment do
include ActiveSupport
File.open('config/initializers/secret_token.rb', 'w') do |f|
f.puts "#{Rails.application.class.parent_name}::Application.config.secret_token = '#{SecureRandom.hex(30)}'"
end
end
name of the Rails app as it was spelled when you did a "rails new your-app-name"
app_name = Rails.application.config.session_options[:key].sub(/^_/,'').sub(/_session/,'')
=> 'your-app-name'
This works very reliable, even if the app directory gets renamed during deployment, and you don't have to take a guess on how to get from the Class name to the correct spelling that was used during 'rails new'.
Using this, you could do this:
class << Rails.application
def name
Rails.application.config.session_options[:key].sub(/^_/,'').sub(/_session/,'')
end
end
Rails.application.name
=> 'test-app'
精彩评论