Sha256: 90dda879b8ff810deba6fe20447206ed292b456f3c282ceb51f0d964c93c2cce

Contents?: true

Size: 1.21 KB

Versions: 5

Compression:

Stored size: 1.21 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 = false
      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.6 lib/bait/phase.rb
bait-0.5.5 lib/bait/phase.rb
bait-0.5.4 lib/bait/phase.rb
bait-0.5.2 lib/bait/phase.rb
bait-0.5.1 lib/bait/phase.rb