Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an install generator for a Ruby gem

I'm pretty new to building Ruby gems and am taking a stab at my first one. I'm in the middle of writing a generator for my gem that will generate a migration in my Rails app. I'm looking to simply include the gem in the Rails application, run "rails g mygem:install" to have it create the migrations, then run "rake db:migrate" to finalize everything.

I've found several different ways to accomplish similar tasks, but so far nothing has worked. I cannot seem to get the Rails application to find the generator. The latest guide I've tried is located here: http://www.railsdispatch.com/posts/how-rails-3-enables-more-choices-part-1.

Here is what my current gem structure looks like:

-lib/
  -generators/
    -templates/
      -some_migration.rb
    -install_generator.rb
  -gemname/
    -rails/
      -railtie.rb
      -engine.rb
      -tasks/
        -gemname.rake
  -gemname.rb
 -spec/
 -gemname.gemspec

Here is what my install_generator.rb file looks like:

require 'rails'

module Gemname
  class InstallGenerator < ::Rails::Generators::Base
    include Rails::Generators::Migration
    source_root File.expand_path('../templates', __FILE__)

    desc "add the migrations"
    def self.next_migration_number(path)
      unless @prev_migration_nr
        @prev_migration_nr = Time.now.utc.strftime("%Y%m%d%H%M%S").to_i
      else
        @prev_migration_nr += 1
      end
     @prev_migration_nr.to_s
    end

    def copy_migrations
     migration_template "some_migration.rb", "db/migrate/some_migration.rb"
    end
  end
end

I'm not sure if there's something I'm missing. I'm testing with a Rails 3.2 application that has my gem listed in its Gemfile and the gem is installed. Is there anything wrong with gem folder structure that might be preventing my generator from showing up? Do I need to require something somewhere?

Any help is appreciated.

like image 864
Joel Andritsch Avatar asked Nov 29 '12 05:11

Joel Andritsch


2 Answers

Rails no longer automatically loads everything in lib by default, like it used to. For a few methods of requiring your files, check out the answers to this question - Best way to load module/class from lib folder in Rails 3?.

like image 159
Brad Werth Avatar answered Sep 17 '22 17:09

Brad Werth


Well, I'm not sure which of the changes I made fixed my problem, but here is what I did:

Changed the name of my generator to gemname_generator.rb and the directory structure of my generator to this:

- lib/
  -generators/
    -templates/
    -gemname_generator.rb

Added this line to my generator:

namespace 'gemname'

I'm now able to run "rails g gemname" in my Rails application and have it call my generator.

like image 38
Joel Andritsch Avatar answered Sep 19 '22 17:09

Joel Andritsch