Ruby on rails 3 如何在运行“rails generate”时防止初始值设定项运行`

Ruby on rails 3 如何在运行“rails generate”时防止初始值设定项运行`,ruby-on-rails-3,initialization,Ruby On Rails 3,Initialization,我想用初始值设定项预填充缓存,但我不需要每次运行rake或rails g等时都运行此代码。rake和Bundler很容易处理,但类似的解决方案不适用于生成器: # config/initializers/prepop_cache.rb if !defined?(::Bundler) and !defined?(::Rake) and !defined(Rails::Generators) # do stuff end 这一定是因为运行时rails/generators(或类似的东西)是re

我想用初始值设定项预填充缓存,但我不需要每次运行
rake
rails g
等时都运行此代码。rake和Bundler很容易处理,但类似的解决方案不适用于生成器:

# config/initializers/prepop_cache.rb
if !defined?(::Bundler) and !defined?(::Rake) and !defined(Rails::Generators)
  # do stuff
end
这一定是因为运行时
rails/generators
(或类似的东西)是
require
ed。如何检查正在运行的命令是否为
rails g xyz

更新:

这里可以找到两种解决方案:


我仍然想知道是否有可能以我上面尝试过的方式实现。

Rails 3中,您希望做的事情是可以想象的,但是以一种令人讨厌的方式。以下是方法:

进行
rails generate
调用时,调用路径如下所示:

  • 被称为,它最终会将您路由到
  • 执行需要
  • 是加载的,这是主要的焦点
在为生成而运行的代码中:

ARGV << '--help' if ARGV.empty?

aliases = {
  "g"  => "generate",
  "c"  => "console",
  "s"  => "server",
  "db" => "dbconsole"
}

command = ARGV.shift                       # <= #1
command = aliases[command] || command

case command
when 'generate', 'destroy', 'plugin', 'benchmarker', 'profiler'
  require APP_PATH
  Rails.application.require_environment!   # <= #2
  require "rails/commands/#{command}"      # <= #3
如您所见,没有发电机正在运行的直接信息。也就是说,有间接的信息。即
ARGV[0]#=>“model”
。可以想象,您可以创建一个可能的生成器列表,并检查该生成器是否已在
ARGV[0]
上被调用。我的负责开发人员说,这是一个黑客,可能会以你意想不到的方式破坏,所以我会谨慎使用

唯一的另一个选择是按照您的建议修改
script/rails
——这是一个不错的解决方案,但在升级到rails 4时可能会中断


在Rails 4中,您有了更多的希望!到的时候,生成器名称空间已经加载。这意味着您可以在初始值设定项中执行以下操作:

if defined? Rails::Generators   #=> "constant"
  # code to run if generators loaded
else
  # code to run if generators not loaded
end
if defined? Rails::Generators   #=> "constant"
  # code to run if generators loaded
else
  # code to run if generators not loaded
end