Rails 3.1:如何仅为 Web 应用程序运行初始化程序(rails server/unicorn/etc) [英] Rails 3.1: how to run an initializer only for the web app (rails server/unicorn/etc)
问题描述
我的 web 应用程序需要加密其会话数据.我的设置是:
config/initializers/encryptor.rb:需要'openssl'需要我的应用程序/加密器"MyApp::Encryptor.config[:random_key] = OpenSSL::Random.random_bytes(128)Session.delete_all应用程序/模型/session.rb:需要'attr_encrypted'课时proc { MyApp::Encryptor.config[ :random_key ] }, :marshal =>真的# 其余模型内容结尾
这一切都很好,并且保证了会话数据的安全.问题是:当我运行我的自定义 rake 任务时,它会加载初始化程序并清除所有会话.不好!</p>
我可以在我的初始化程序中放入什么来确保它只为 webapp 初始化运行?或者,我可以在我的初始化程序中放入什么以使其不为 rake 任务运行?
更新: 好的,我目前所做的是添加 MYAPP_IN_RAKE = true 除非已定义?MYAPP_IN_RAKE
到我的 .rake 文件.然后在我的初始化程序中:
除非已定义?( MYAPP_IN_RAKE ) &&MYAPP_IN_RAKE# 仅 Web 初始化结尾
似乎有效.但我愿意接受其他建议.
你可以像这样在 `config/application.rb' 中修改你的应用程序:
模块 MyAppdef self.rake?!!@耙结尾def self.rake=(值)@rake = !!值结尾
然后在您的 Rakefile
中添加:
MyApp.rake = true
最好使用方法而不是常量,因为有时您希望稍后更改或重新定义它们.另外,它们不会污染根命名空间.
这是一个示例 config/initializers/rake_environment_test.rb
脚本:
if (MyApp.rake?)把在耙子里"别的把不在耙子里"结尾
Rakefile
的可编程特性为您提供了极大的灵活性.
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.
这篇关于Rails 3.1:如何仅为 Web 应用程序运行初始化程序(rails server/unicorn/etc)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!