rails data migrations, part 2


class DataMigration < ActiveRecord::Migration

  class << self

    def fixtures(file_name, options = { :folder => 'data' })
      @file_name, @folder_name = file_name, options[:folder]
    end

    def migrate(direction)
      super(direction) # perform migration
      if direction == :up && valid_options_present?
        require 'active_record/fixtures'
        data_migration_path = "#{RAILS_ROOT}/db/migrate/#{@folder_name}"
        Fixtures.create_fixtures(data_migration_path, @file_name.to_s)
        say "DataMigration INFO"
        say "Loaded #{data_migration_path}/#{@file_name.to_s}.yml", true
      end
    rescue Errno::ENOENT => e
      say "Snusnu::DataMigration WARNING"
      say e.message, true
    end

    private

    def valid_options_present?
      [ @file_name, @folder_name ].all? do |v|
        v && (v.is_a?(String) || v.is_a?(Symbol))
      end
    end

  end

end

class CreateMyMigration < DataMigration
  fixtures :people #, :folder => "fixtures"
  def self.up
    create_table :people, :force => true do |t|
      #...
    end
  end
end


Leave a Reply

Formatting: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>