Class: FileTransactions::BaseCommand
- Inherits:
-
Object
- Object
- FileTransactions::BaseCommand
- Defined in:
- lib/file_transactions/base_command.rb
Overview
A Base class that all commands must inherit from.
This class provides all the necessary methods/hooks to make it possible to group commands together and/or nested inside transactions (and other commands).
Direct Known Subclasses
ChangeFileCommand, CreateDirectoryCommand, CreateFileCommand, DeleteFileCommand, MoveFileCommand
Class Method Summary collapse
Instance Method Summary collapse
-
#execute ⇒ Object
Execute the command.
-
#executed? ⇒ Boolean
Returns true of false depending on if the commands has been executed.
-
#failed? ⇒ Boolean
Returns true if the command has been unsuccessfully executed, otherwise false.
-
#register(command) ⇒ Object
This registers a nested command.
-
#undo ⇒ Object
Undo the changes made from a previous call to #execute.
Class Method Details
.execute(*args, **kwargs, &block) ⇒ Object
10 11 12 13 14 15 16 |
# File 'lib/file_transactions/base_command.rb', line 10 def self.execute(*args, **kwargs, &block) if RUBY_VERSION < '3.0' && kwargs.empty? new(*args, &block).tap { |cmd| cmd.execute } else new(*args, **kwargs, &block).tap { |cmd| cmd.execute } end end |
Instance Method Details
#execute ⇒ Object
Execute the command. This will trigger the following methods:
* #before
* #execute!
* #after
22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/file_transactions/base_command.rb', line 22 def execute scope = Transaction.scope scope&.register self prepare run_before run_excecute.tap { run_after } rescue StandardError self.failure_state = state raise ensure Transaction.scope = scope end |
#executed? ⇒ Boolean
Returns true of false depending on if the commands has been executed.
54 55 56 |
# File 'lib/file_transactions/base_command.rb', line 54 def executed? !!executed end |
#failed? ⇒ Boolean
Returns true if the command has been unsuccessfully executed, otherwise false.
59 60 61 |
# File 'lib/file_transactions/base_command.rb', line 59 def failed? !!failure_state end |
#register(command) ⇒ Object
This registers a nested command. This method is called whever a command is executed and should not be called manually.
49 50 51 |
# File 'lib/file_transactions/base_command.rb', line 49 def register(command) sub_commands[state] << command end |
#undo ⇒ Object
Undo the changes made from a previous call to #execute. All previouly executed commands will be undone in reverse order.
37 38 39 40 41 42 43 44 45 |
# File 'lib/file_transactions/base_command.rb', line 37 def undo raise Error, "Cannot undo #{self.class} which hasn't been executed" unless executed? sub_commands[:after].reverse_each(&:undo) ret = undo! unless failure_state == :before sub_commands[:before].reverse_each(&:undo) ret end |