edge badge

ActiveRecord::Migration::CommandRecorder records commands done during a migration and knows how to reverse those commands. The CommandRecorder knows how to invert the following commands:

  • add_column

  • add_index

  • add_timestamps

  • create_table

  • create_join_table

  • remove_timestamps

  • rename_column

  • rename_index

  • rename_table

Namespace
Methods
C
I
N
R
Included Modules
Attributes
[RW] commands
[RW] delegate
[RW] reverting
Class Public methods
new(delegate = nil)
# File activerecord/lib/active_record/migration/command_recorder.rb, line 21
def initialize(delegate = nil)
  @commands = []
  @delegate = delegate
  @reverting = false
end
Instance Public methods
change_table(table_name, options = {})
# File activerecord/lib/active_record/migration/command_recorder.rb, line 90
def change_table(table_name, options = {})
  yield delegate.update_table_definition(table_name, self)
end
inverse_of(command, args, &block)

Returns the inverse of the given command. For example:

recorder.inverse_of(:rename_table, [:old, :new])
# => [:rename_table, [:new, :old]]

This method will raise an IrreversibleMigration exception if it cannot invert the command.

# File activerecord/lib/active_record/migration/command_recorder.rb, line 63
def inverse_of(command, args, &block)
  method = :"invert_#{command}"
  raise IrreversibleMigration unless respond_to?(method, true)
  send(method, args, &block)
end
record(*command, &block)

record command. command should be a method name and arguments. For example:

recorder.record(:method_name, [:arg1, :arg2])
# File activerecord/lib/active_record/migration/command_recorder.rb, line 48
def record(*command, &block)
  if @reverting
    @commands << inverse_of(*command, &block)
  else
    @commands << (command << block)
  end
end
revert()

While executing the given block, the recorded will be in reverting mode. All commands recorded will end up being recorded reverted and in reverse order. For example:

recorder.revert{ recorder.record(:rename_table, [:old, :new]) }
# same effect as recorder.record(:rename_table, [:new, :old])
# File activerecord/lib/active_record/migration/command_recorder.rb, line 34
def revert
  @reverting = !@reverting
  previous = @commands
  @commands = []
  yield
ensure
  @commands = previous.concat(@commands.reverse)
  @reverting = !@reverting
end