Sha256: 5d34ac58e92b71ab28802ce82088b867473232156ecf72807d15b33c963fd897

Contents?: true

Size: 1.52 KB

Versions: 15

Compression:

Stored size: 1.52 KB

Contents

require 'hyperion/aux/util'
require 'hyperion/types/hyperion_result'
require 'hyperion/types/client_error_detail'

class Hyperion
  # This is a DSL of sorts that gives the `request` block a nice way
  # to dispatch the result based on status, HTTP code, etc.
  module DispatchDsl

    def __set_escape_continuation__(k)
      @escape = k
    end

    def when(condition, &action)
      pred = as_predicate(condition)
      is_match = Util.nil_if_error { Proc.loose_call(pred, [self]) }
      if is_match
        return_value = action.call(self)
        @escape.call(return_value)  # non-local exit
      else
        nil
      end
    end

    private

    def as_predicate(condition)
      if condition.is_a?(HyperionStatus)
        status_checker(condition)

      elsif condition.is_a?(ClientErrorCode)
        client_error_code_checker(condition)

      elsif condition.is_a?(Integer)
        http_code_checker(condition)

      elsif condition.is_a?(Range)
        range_checker(condition)

      elsif condition.callable?
        condition

      else
        fail "Not a valid condition: #{condition.inspect}"
      end
    end

    def status_checker(status)
      proc { |r| r.status == status }
    end

    def client_error_code_checker(code)
      proc do |r|
        r.status == HyperionStatus::CLIENT_ERROR &&
            r.body.errors.detect(:code, code)
      end
    end

    def http_code_checker(code)
      proc { |r| r.code == code }
    end

    def range_checker(range)
      proc { |r| range.include?(r.code) }
    end
  end
end

Version data entries

15 entries across 15 versions & 1 rubygems

Version Path
hyperion_http-0.6.0 lib/hyperion/result_handling/dispatch_dsl.rb
hyperion_http-0.5.0 lib/hyperion/result_handling/dispatch_dsl.rb
hyperion_http-0.3.0 lib/hyperion/result_handling/dispatch_dsl.rb
hyperion_http-0.2.4 lib/hyperion/result_handling/dispatch_dsl.rb
hyperion_http-0.2.3 lib/hyperion/result_handling/dispatch_dsl.rb
hyperion_http-0.2.2 lib/hyperion/result_handling/dispatch_dsl.rb
hyperion_http-0.2.1 lib/hyperion/result_handling/dispatch_dsl.rb
hyperion_http-0.1.9 lib/hyperion/result_handling/dispatch_dsl.rb
hyperion_http-0.1.8 lib/hyperion/result_handling/dispatch_dsl.rb
hyperion_http-0.1.7 lib/hyperion/result_handling/dispatch_dsl.rb
hyperion_http-0.1.6 lib/hyperion/result_handling/dispatch_dsl.rb
hyperion_http-0.1.5 lib/hyperion/result_handling/dispatch_dsl.rb
hyperion_http-0.1.4 lib/hyperion/result_handling/dispatch_dsl.rb
hyperion_http-0.1.3 lib/hyperion/result_handling/dispatch_dsl.rb
hyperion_http-0.1.2 lib/hyperion/result_handling/dispatch_dsl.rb