aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/migration/command_recorder.rb
blob: 25b8649350a17a079c965152834d646149d26069 (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
module ActiveRecord
  class Migration
    # ActiveRecord::Migration::CommandRecorder records commands done during
    # a migration and knows how to reverse those commands.
    class CommandRecorder
      attr_reader :commands

      def initialize
        @commands = []
      end

      # record +command+.  +command+ should be a method name and arguments.
      # For example:
      #
      #   recorder.record(:method_name, [:arg1, arg2])
      def record(*command)
        @commands << command
      end

      # Returns a list that represents commands that are the inverse of the
      # commands stored in +commands+.
      def inverse
        @commands.map { |name, args| send(:"invert_#{name}", args) }
      end

      private
      def invert_create_table(args)
        [:drop_table, args]
      end

      def invert_rename_table(args)
        [:rename_table, args.reverse]
      end

      def invert_add_column(args)
        [:remove_column, args.first(2)]
      end

      def invert_rename_index(args)
        [:rename_index, args.reverse]
      end

      def invert_rename_column(args)
        [:rename_column, [args.first] + args.last(2).reverse]
      end
    end
  end
end