Search code examples
ruby-on-railsrubyrakeinitializerrake-task

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.


Solution

  • 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.