简体   繁体   中英

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_NAME'] . 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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM