module Roda::RodaPlugins::Monads::RequestMethods

Extends {Roda::RodaRequest#block_result}’s with an ability to respond to `Dry::Monads::Result` or compatible object (that responds to `#to_either` method, returning `Dry::Monads::Result`).

Public Instance Methods

block_result(result) click to toggle source

Handle match block return values. By default, if a string is given and the response is empty, use the string as the response body.

Calls superclass method
# File lib/roda/plugins/monads.rb, line 74
def block_result(result)
  return super(result) unless result.respond_to?(:to_either)
  respond_with_either(result)
end

Private Instance Methods

match_either(either) click to toggle source

@param [Dry::Monads::Result, to_either] either

# File lib/roda/plugins/monads.rb, line 82
def match_either(either)
  either = either.to_either if respond_to?(:to_either)
  matcher = if rack_either?(either)
              :rack_either
            elsif either.right?
              :right
            else
              :left
            end
  instance_exec(either, &roda_class.either_matcher(matcher))
end
match_left(either) click to toggle source

@param [Dry::Monads::Result::Failure] either

# File lib/roda/plugins/monads.rb, line 102
def match_left(either)
  return false unless either.left?
  response.status, body = either.failure
  populate_body(body)
  true
end
match_rack_either(either) click to toggle source
# File lib/roda/plugins/monads.rb, line 109
def match_rack_either(either)
  response.status, headers, body = either.value_or(&:itself)
  headers.each { |header, value| response.headers[header] = value }
  populate_body(body)
  true
end
match_right(either) click to toggle source

@param [Dry::Monads::Result::Success] either

# File lib/roda/plugins/monads.rb, line 95
def match_right(either)
  return false unless either.right?
  populate_body(either.success)
  true
end
populate_body(body) click to toggle source

@param [String, Object] body

# File lib/roda/plugins/monads.rb, line 123
def populate_body(body)
  response.write block_result_body(body) if response.empty?
end
rack_either?(either) click to toggle source

@param [Dry::Monads::Result] either

# File lib/roda/plugins/monads.rb, line 117
def rack_either?(either)
  value = either.value_or(&:itself)
  value.is_a?(Array) && value.size == 3
end
respond_with_either(either) click to toggle source

@param [Dry::Monads::Result, to_either] either @return [void]

# File lib/roda/plugins/monads.rb, line 129
def respond_with_either(either)
  instance_exec either, &roda_class.either_matcher(:either)
end