Class: FileTransactions::ChangeFileCommand

Inherits:
BaseCommand
  • Object
show all
Defined in:
lib/file_transactions/change_file_command.rb

Overview

This command supports making changes to files. The block passed to ::new must either return a String, in which case the file content will be replace with that string. Or the block must itself modify the file with desired changes (and return anything but a String).

When this command has been executed, the file can be restored to the previous state again by calling #undo.

Examples

# Pass in the filename  name to ::new
cmd1 = ChangeFileCommand.new('some_existing_file') do
  <<~EOF
    Some content to that should
    replace the current file content.
  EOF
end

# Files can also be modified manually.
# Note: the block gets name as argument.
cmd2 = ChangeFileCommand.new('another_existing_file') do |name|
  File.open(name, 'a') do |f|
    f.write("Add some more stuff at the end\n")
  end
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from BaseCommand

execute, #execute, #executed?, #failed?, #register, #undo

Constructor Details

#initialize(name, &block) ⇒ ChangeFileCommand

Returns a new instance of ChangeFileCommand.

Parameters:

  • name (String)

    The name of the file to be changed. May be just a name or an absolut or relative path



36
37
38
39
# File 'lib/file_transactions/change_file_command.rb', line 36

def initialize(name, &block)
  @name = name
  @block = block
end

Instance Attribute Details

#blockObject (readonly)

Returns the value of attribute block.



33
34
35
# File 'lib/file_transactions/change_file_command.rb', line 33

def block
  @block
end

#nameObject (readonly)

Returns the value of attribute name.



33
34
35
# File 'lib/file_transactions/change_file_command.rb', line 33

def name
  @name
end