0

I have a simple rails install generator for an engine I'm making:

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

When a user runs rails g bouncer:install, a locale file is copied into their app. I also want to copy in my migrations, but rather than use copy_file method, I was hoping I could just run rake bouncer_engine:install:migrations inside the generator, like I would do from the command line. How can I do this?

stephenmurdoch
  • 34,024
  • 29
  • 114
  • 189

2 Answers2

4

The correct way to do this:

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

This saves a lot of hassle and even takes care of the making sure each migration's name is timestamped properly.

stephenmurdoch
  • 34,024
  • 29
  • 114
  • 189
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?

Vapire
  • 4,568
  • 3
  • 24
  • 41
  • yeah, I am trying to make it run as part of the install task, I take it you can't just run a rake task inside a generator then? – stephenmurdoch Apr 07 '12 at 11:26
  • Not directly by re-using your code, as far as I know. But running the rake command as a shell command from your code should work... you just have to make sure to execute it in the right directory – Vapire Apr 07 '12 at 11:30
  • ahh, thanks for your info. I was tring to use ` Rake::Task['rake bouncer_engine:install:migrations'].execute` from inside my generator but now I'm just going to do what you say and copy the files over using [this technique](http://www.dixis.com/?p=444) – stephenmurdoch Apr 07 '12 at 12:50
  • Actually, I've added an answer which shows how to do this. I borrowed the technique from refinerycms. Thanks for your help anyway, – stephenmurdoch Apr 08 '12 at 20:06
  • Ah... good! I didn't know this :) But you should mark it as answered. – Vapire Apr 09 '12 at 08:58