Rails 3.1: how to start the initializer for a web application only (rails / unicorn / etc server)

My webapp should encrypt my session data. I am setting up:

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 

Everything works fine and saves session data. This is where the problem arises: when I run my custom rake tasks, it loads the initializer and clears all sessions. Not good!

What can I add to my initializer to make sure that it ONLY runs to initialize the webapp? Or, what can I put in my initializer so that it does NOT start for rake tasks?

Update: OK, what have I done so far, adds MYAPP_IN_RAKE = true unless defined? MYAPP_IN_RAKE 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 

It seems to need work. But I am open to other suggestions.

+6
source share
2 answers

You can make changes to your application in `config / application.rb 'as follows:

 module MyApp def self.rake? !!@rake end def self.rake=(value) @rake = !!value end 

Then in Rakefile you would add this:

 MyApp.rake = true 

It's nice to use methods, not constants, because sometimes you prefer to change them or redefine them later. In addition, they do not pollute the root namespace.

Here, an example of config/initializers/rake_environment_test.rb script:

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

The programmatic nature of Rakefile gives you considerable flexibility.

+8
source

There is one more work:

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

When starting from a rake, your ENV ["RAILS_ENV"] will be zero. The β€œtest” test is to avoid starting when using rspec.

I know that rely on the use of Rails.env, but it returns "development" when it is not initialized.

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 
+2
source

Source: https://habr.com/ru/post/897791/


All Articles