0

我有一个简单的 rails install generator 用于我正在制作的引擎:

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在生成器中运行,就像我从命令行做的那样。我怎样才能做到这一点?

4

2 回答 2

4

这样做的正确方法:

#!/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

这节省了很多麻烦,甚至可以确保每个迁移的名称都带有正确的时间戳。

于 2012-04-08T20:04:32.713 回答
1

Well, I think it should be possible by just executing the shell command. Here are 6 different ways to execute a shell command in ruby.

But my other suggestion would be instead of implementing it as a rake task, to direcly implement it as part of your generator... I don't know what your exact demands are, but given your description it seems to me that the migrations-task only runs once, when you execute the install task? Or is there a special need to offer it as a rake task as well?

于 2012-04-07T11:19:35.620 回答