aboutsummaryrefslogtreecommitdiffstats
path: root/railties/lib/rails/generators/migration.rb
blob: 57c36f56689531ce11b03439e8f175f7a3d06e38 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
require "active_support/concern"
require_relative "actions/create_migration"

module Rails
  module Generators
    # Holds common methods for migrations. It assumes that migrations have the
    # [0-9]*_name format and can be used by other frameworks (like Sequel)
    # just by implementing the next migration version method.
    module Migration
      extend ActiveSupport::Concern
      attr_reader :migration_number, :migration_file_name, :migration_class_name

      module ClassMethods #:nodoc:
        def migration_lookup_at(dirname)
          Dir.glob("#{dirname}/[0-9]*_*.rb")
        end

        def migration_exists?(dirname, file_name)
          migration_lookup_at(dirname).grep(/\d+_#{file_name}.rb$/).first
        end

        def current_migration_number(dirname)
          migration_lookup_at(dirname).collect do |file|
            File.basename(file).split("_").first.to_i
          end.max.to_i
        end

        def next_migration_number(dirname)
          raise NotImplementedError
        end
      end

      def create_migration(destination, data, config = {}, &block)
        action Rails::Generators::Actions::CreateMigration.new(self, destination, block || data.to_s, config)
      end

      def set_migration_assigns!(destination)
        destination = File.expand_path(destination, destination_root)

        migration_dir = File.dirname(destination)
        @migration_number     = self.class.next_migration_number(migration_dir)
        @migration_file_name  = File.basename(destination, ".rb")
        @migration_class_name = @migration_file_name.camelize
      end

      # Creates a migration template at the given destination. The difference
      # to the default template method is that the migration version is appended
      # to the destination file name.
      #
      # The migration version, migration file name, migration class name are
      # available as instance variables in the template to be rendered.
      #
      #   migration_template "migration.rb", "db/migrate/add_foo_to_bar.rb"
      def migration_template(source, destination, config = {})
        source = File.expand_path(find_in_source_paths(source.to_s))

        set_migration_assigns!(destination)
        context = instance_eval("binding")

        dir, base = File.split(destination)
        numbered_destination = File.join(dir, ["%migration_number%", base].join("_"))

        create_migration numbered_destination, nil, config do
          ERB.new(::File.binread(source), nil, "-", "@output_buffer").result(context)
        end
      end
    end
  end
end