Class: Patir::RubyCommand
- Inherits:
-
Object
- Object
- Patir::RubyCommand
- Includes:
- Command
- Defined in:
- lib/patir/command.rb
Overview
This class allows you to wrap Ruby blocks and handle them like Command
Provide a block to RubyCommand#new and you can execute the block using RubyCommand#run
The block receives the instance of RubyCommand so you can set the output and error output.
If the block runs to the end the command is considered successful.
Raising an exception in the block will set the command status to :error.
The exception message will be appended to the error output of the command
Examples
An example (using the excellent HighLine lib) of a CLI prompt as a RubyCommand RubyCommand.new(“prompt”) do |cmd|
cmd.output=""
cmd.error=""
unless HighLine.agree("#{step.text}?")
cmd.error="Why not?"
raise "You did not agree"
end
end
Instance Attribute Summary collapse
-
#cmd ⇒ Object
readonly
Returns the value of attribute cmd.
-
#context ⇒ Object
readonly
Returns the value of attribute context.
-
#working_directory ⇒ Object
readonly
Returns the value of attribute working_directory.
Attributes included from Command
#error, #exec_time, #name, #number, #output, #status, #strategy
Instance Method Summary collapse
-
#initialize(name, working_directory = nil, &block) ⇒ RubyCommand
constructor
A new instance of RubyCommand.
-
#run(context = nil) ⇒ Object
Runs the associated block.
Methods included from Command
#executed?, #reset, #run?, #success?
Constructor Details
#initialize(name, working_directory = nil, &block) ⇒ RubyCommand
Returns a new instance of RubyCommand.
482 483 484 485 486 487 488 489 490 |
# File 'lib/patir/command.rb', line 482 def initialize name,working_directory=nil,&block @name=name @working_directory=working_directory||"." if block_given? @cmd=block else raise "You need to provide a block" end end |
Instance Attribute Details
#cmd ⇒ Object (readonly)
Returns the value of attribute cmd.
481 482 483 |
# File 'lib/patir/command.rb', line 481 def cmd @cmd end |
#context ⇒ Object (readonly)
Returns the value of attribute context.
481 482 483 |
# File 'lib/patir/command.rb', line 481 def context @context end |
#working_directory ⇒ Object (readonly)
Returns the value of attribute working_directory.
481 482 483 |
# File 'lib/patir/command.rb', line 481 def working_directory @working_directory end |
Instance Method Details
#run(context = nil) ⇒ Object
Runs the associated block
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 |
# File 'lib/patir/command.rb', line 492 def run context=nil @run=true @context=context @error="" @output="" begin t1=Time.now Dir.chdir(@working_directory) do @cmd.call(self) @status=:success end rescue StandardError @error<<"\n#{$!.}" @error<<"\n#{$!.backtrace}" if $DEBUG @status=:error ensure @exec_time=Time.now-t1 end @context=nil return @status end |