开发者

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

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.


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜