5. Create a migration generator

When you created the plugin above, you specified the —with-generator option, so you already have the generator stubs in your plugin.

We'll be relying on the built-in rails generate template for this tutorial. Going into the details of generators is beyond the scope of this tutorial.

Type:

script/generate

You should see the line:

Plugins (vendor/plugins): yaffle

When you run script/generate yaffle you should see the contents of your USAGE file. For this plugin, the USAGE file looks like this:

Description:
    Creates a migration that adds yaffle squawk fields to the given model

Example:
    ./script/generate yaffle hickwall

    This will create:
        db/migrate/TIMESTAMP_add_yaffle_fields_to_hickwall

Now you can add code to your generator:

# File: vendor/plugins/yaffle/generators/yaffle/yaffle_generator.rb

class YaffleGenerator < Rails::Generator::NamedBase
  def manifest
    record do |m|
      m.migration_template 'migration:migration.rb', "db/migrate", {:assigns => yaffle_local_assigns,
        :migration_file_name => "add_yaffle_fields_to_#{custom_file_name}"
       }
    end
  end

  private
    def custom_file_name
      custom_name = class_name.underscore.downcase
      custom_name = custom_name.pluralize if ActiveRecord::Base.pluralize_table_names
    end

    def yaffle_local_assigns
      returning(assigns = {}) do
        assigns[:migration_action] = "add"
        assigns[:class_name] = "add_yaffle_fields_to_#{custom_file_name}"
        assigns[:table_name] = custom_file_name
        assigns[:attributes] = [Rails::Generator::GeneratedAttribute.new("last_squawk", "string")]
        assigns[:attributes] << Rails::Generator::GeneratedAttribute.new("last_squawked_at", "datetime")
      end
    end
end

Note that you need to be aware of whether or not table names are pluralized.

This does a few things:

  • Reuses the built in rails migration_template method.

  • Reuses the built-in rails migration template.

When you run the generator like

script/generate yaffle bird

You will see a new file:

# File: db/migrate/20080529225649_add_yaffle_fields_to_birds.rb

class AddYaffleFieldsToBirds < ActiveRecord::Migration
  def self.up
    add_column :birds, :last_squawk, :string
    add_column :birds, :last_squawked_at, :datetime
  end

  def self.down
    remove_column :birds, :last_squawked_at
    remove_column :birds, :last_squawk
  end
end