Sha256: e096958ace640260f18f7d8f9c969eca890df0eb651e3c7fa27bf49c92338050

Contents?: true

Size: 1.23 KB

Versions: 3

Compression:

Stored size: 1.23 KB

Contents

require 'ostruct'
require 'sanford-protocol'

require 'sanford/logger'

module Sanford

  class Runner

    ResponseArgs = Struct.new(:status, :data)

    attr_reader :handler_class, :request, :logger

    def initialize(handler_class, request, logger = nil)
      @handler_class, @request = handler_class, request
      @logger = logger || Sanford::NullLogger.new
      @handler = @handler_class.new(self)
    end

    def run
      response_args = catch_halt do
        @handler.init
        @handler.run
      end
      Sanford::Protocol::Response.new(response_args.status, response_args.data)
    end

    module HaltMethods

      # It's best to keep what `halt` and `catch_halt` return in the same format.
      # Currently this is a `ResponseArgs` object. This is so no matter how the
      # block returns (either by throwing or running normally), you get the same
      # thing kind of object.

      def halt(status, options = nil)
        options = OpenStruct.new(options || {})
        response_status = [ status, options.message ]
        throw :halt, ResponseArgs.new(response_status, options.data)
      end

      def catch_halt(&block)
        catch(:halt){ ResponseArgs.new(*block.call) }
      end

    end
    include HaltMethods

  end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
sanford-0.4.0 lib/sanford/runner.rb
sanford-0.3.0 lib/sanford/runner.rb
sanford-0.2.0 lib/sanford/runner.rb