Rails 3.1:如何仅为Web应用程序运行初始化程序(rails server / unicorn / etc)

我的webapp需要加密其会话数据。 我设置的是:

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  proc { MyApp::Encryptor.config[ :random_key ] }, :marshal => true # Rest of model stuff end 

一切都很好,并保证会话数据安全。 这是问题所在:当我运行自定义rake任务时,它会加载初始化程序并清除所有会话。 不好!

我可以在初始化程序中放置什么来确保它仅用于webapp初始化? 或者,我可以在初始化程序中添加什么来使其不用于rake任务?

更新:好的,我现在所做的是添加MYAPP_IN_RAKE = true unless defined? MYAPP_IN_RAKE MYAPP_IN_RAKE = true unless defined? MYAPP_IN_RAKE到我的.rake文件。 然后在我的初始化程序中我做:

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

似乎工作。 但我愿意接受其他建议。

您可以在`config / application.rb’中对您的应用程序进行修改,如下所示:

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

然后在您的Rakefile添加以下内容:

 MyApp.rake = true 

使用方法而不是常量是很好的,因为有时您更愿意稍后更改或重新定义它们。 另外,它们不会污染根命名空间。

这是一个示例config/initializers/rake_environment_test.rb脚本:

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

Rakefile的可编程特性为您提供了极大的灵活性。

还有另一项工作:

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

使用rake启动时,ENV [“RAILS_ENV”]将为零。 ‘test’的测试是避免在使用rspec时运行。

我知道这是使用Rails.env,但它没有初始化时返回“开发”。

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