Sha256: 20a366622e684bf9a9a25e1d4e3322145cfac9cfc3119a745055e80e969a59e6

Contents?: true

Size: 1.26 KB

Versions: 5

Compression:

Stored size: 1.26 KB

Contents

module Bait
  class Phase
    class UnexpectedHandlerDefinition < StandardError ; end
    POSSIBLE_HANDLERS = %w(init output rescue missing done)

    def initialize script
      @script = script
      @handlers = {}
    end

    def handle name, &block
      if POSSIBLE_HANDLERS.include? name.to_s
        @handlers[name] = block
      else
        raise UnexpectedHandlerDefinition
      end
      self
    end

    alias_method :on, :handle

    def run!
      if File.exists?(@script)
        handler(:init)
        zerostatus = execute_subprocess do |output_line|
          handler(:output, output_line)
        end
        handler(:done, zerostatus)
      else
        msg = "Script #{@script} was expected but is missing."
        handler(:missing, msg)
      end
    end

    private

    def handler name, *args
      if target = @handlers[name]
        target.call(*args)
      end
    end

    def execute_subprocess &block
      zerostatus = 'unknown'
      block.call("\nExecuting #{@script}\n\n")
      Open3.popen2e(@script) do |stdin, oe, wait_thr|
        oe.each {|line| block.call(line) }
        zerostatus = wait_thr.value.exitstatus == 0
      end
    rescue => ex
      handler(:rescue, ex)
      zerostatus = false
    ensure
      return zerostatus
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
bait-0.5.13 lib/bait/phase.rb
bait-0.5.12 lib/bait/phase.rb
bait-0.5.11 lib/bait/phase.rb
bait-0.5.10 lib/bait/phase.rb
bait-0.5.9 lib/bait/phase.rb