Class: Patir::RubyCommand

Inherits:
Object
  • Object
show all
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

Attributes included from Command

#error, #exec_time, #name, #number, #output, #status, #strategy

Instance Method Summary collapse

Methods included from Command

#executed?, #reset, #run?, #success?

Constructor Details

#initialize(name, working_directory = nil, &block) ⇒ RubyCommand

Returns a new instance of RubyCommand.



468
469
470
471
472
473
474
475
476
# File 'lib/patir/command.rb', line 468

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

#cmdObject (readonly)

Returns the value of attribute cmd.



467
468
469
# File 'lib/patir/command.rb', line 467

def cmd
  @cmd
end

#contextObject (readonly)

Returns the value of attribute context.



467
468
469
# File 'lib/patir/command.rb', line 467

def context
  @context
end

#working_directoryObject (readonly)

Returns the value of attribute working_directory.



467
468
469
# File 'lib/patir/command.rb', line 467

def working_directory
  @working_directory
end

Instance Method Details

#run(context = nil) ⇒ Object

Runs the associated block



478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
# File 'lib/patir/command.rb', line 478

def run context=nil
  @run=true
  @context=context
  begin
    t1=Time.now
    Dir.chdir(@working_directory) do
      @cmd.call(self)
      @status=:success
    end
  rescue StandardError
    error<<"\n#{$!.message}"
    error<<"\n#{$!.backtrace}" if $DEBUG
    @status=:error
  ensure
    @exec_time=Time.now-t1
  end
  @context=nil
  return @status
end