7

我的 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 < ActiveRecord::Base
  attr_accessible :session_id, :data
  attr_encryptor :data, :key => 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到我的 .rake 文件中。然后在我的初始化程序中我这样做:

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

似乎工作。但我对其他建议持开放态度。

4

2 回答 2

9

您可以像这样在 `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为您提供了极大的灵活性。

于 2011-09-22T02:07:16.063 回答
2

还有另一种解决方法:

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
于 2014-02-17T21:38:19.583 回答