2012-04-07 75 views
0

我有一个简单的导轨安装发电机发动机我做:我可以在生成器中运行耙子任务吗?

module Bouncer 
    module Generators 
    class InstallGenerator < Rails::Generators::Base 
     source_root File.expand_path("../../templates", __FILE__) 

     desc "Copies locale file and migrations to your application." 

     def copy_locale 
     copy_file "../../../config/locales/en.yml", "config/locales/bouncer.en.yml" 
     end 

     def copy_migrations 
     # I would like to run "rake bouncer_engine:install:migrations" right here 
     # rather than copy_file "../../../db/migrate/blah.rb", "db/migrate/blah.rb" 
     end 
    end 
    end 
end 

当用户运行rails g bouncer:install,语言环境的文件复制到自己的应用程序。我也想复制我的迁移,但不是使用copy_file方法,我希望我可以在发生器内运行rake bouncer_engine:install:migrations,就像我从命令行执行的那样。我怎样才能做到这一点?

回答

3

正确的方式做到这一点:

#!/usr/bin/env rake 
module Bouncer 
    module Generators 
    class InstallGenerator < Rails::Generators::Base 
     desc "Copies migrations to your application." 
     def copy_migrations 
     rake("bouncer_engine:install:migrations") 
     end  
    end 
    end 
end 

这样可以节省很多的麻烦,甚至负责将确保每个移民的名字正确的时间戳。

1

嗯,我认为应该可以通过执行shell命令。 Here是用ruby执行shell命令的6种不同方法。

但是我的另一个建议是将它作为一个rake任务来实现,而不是将它作为你的发生器的一部分直接实现......我不知道你确切的需求是什么,但考虑到你的描述,在我看来当您执行安装任务时,迁移任务仅运行一次?或者是否有特殊需要将其作为耙子任务提供?

+0

是的,我试图让它作为安装任务的一部分运行,我认为你不能只是在生成器内运行一个rake任务呢? – stephenmurdoch 2012-04-07 11:26:37

+0

据我所知,不是直接通过重新使用您的代码。但是从你的代码运行rake命令作为shell命令应该可以工作......你只需要确保在正确的目录 – Vapire 2012-04-07 11:30:52

+0

ahh中执行它,谢谢你的信息。我正在使用'Rake :: Task ['rake bouncer_engine:install:migrations'] .'执行'在我的生成器中,但现在我只是要做你所说的并使用[这种技术]复制文件http://www.dixis.com/?p=444) – stephenmurdoch 2012-04-07 12:50:46