Rails 3.1: how to run an initializer only for the web app (rails server/unicorn/etc)

a 夏天 提交于 2019-12-07 00:57:17

问题


My webapp needs to encrypt its session data. What I setup is:

config/initializers/encryptor.rb:

require 'openssl'
require 'myapp/encryptor'

MyApp::Encryptor.config[ :random_key ] = OpenSSL::Random.random_bytes( 128 )
Session.delete_all

app/models/session.rb:

require 'attr_encrypted'

class Session < ActiveRecord::Base
  attr_accessible :session_id, :data
  attr_encryptor :data, :key => proc { MyApp::Encryptor.config[ :random_key ] }, :marshal => true

  # Rest of model stuff
end

That all works great, and keeps the session data secured. Here's the problem: when I run my custom rake tasks it loads the initializer and clears all the sessions. Not good!

What can I put in my initializer to make sure it ONLY runs for the webapp initialization? Or, what can I put in my initializer to make it NOT run for rake tasks?

Update: OK, what I've done for the moment is add MYAPP_IN_RAKE = true unless defined? MYAPP_IN_RAKE to my .rake file. And then in my initializer I do:

unless defined?( MYAPP_IN_RAKE ) && MYAPP_IN_RAKE
    # Web only initialization
end

Seems to work. But I'm open to other suggestions.


回答1:


You might make a modification to your application in `config/application.rb' like this:

module MyApp
  def self.rake?
    !!@rake
  end

  def self.rake=(value)
    @rake = !!value
  end

Then in your Rakefile you'd add this:

MyApp.rake = true

It's nice to use methods rather than constants since sometimes you'd prefer to change or redefine them later. Plus, they don't pollute the root namespace.

Here's a sample config/initializers/rake_environment_test.rb script:

if (MyApp.rake?)
  puts "In rake"
else
  puts "Not in rake"
end

The programmable nature of the Rakefile affords you significant flexibility.




回答2:


There is another work around:

unless ENV["RAILS_ENV"].nil? || ENV["RAILS_ENV"] == 'test'

When you launch with rake your ENV["RAILS_ENV"] will be nil. The test for 'test' is to avoid to run when using rspec.

I know that is reckon to use Rails.env but it return "development" when it is not initialised.

http://apidock.com/rails/Rails/env/class

# File railties/lib/rails.rb, line 55
def env
  @_env ||= ActiveSupport::StringInquirer.new(ENV["RAILS_ENV"] 
     || ENV["RACK_ENV"] || "development")
end


来源:https://stackoverflow.com/questions/7508170/rails-3-1-how-to-run-an-initializer-only-for-the-web-app-rails-server-unicorn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!