module Pageflow
  # Allow delegating to another Rack app from a controller action.
  #
  # @api private
  module ControllerDelegation
    # Abort currently executed controller action, call passed Rack app
    # and use its response instead. A block can be passed to mutate
    # the response.
    def delegate_to_rack_app!(app)
      result = app.call(request.env)
      yield(*result) if block_given?

      throw(:delegate, result)
    end

    # Override ActionController::Metal#dispatch [1] which returns the
    # Rack response triple generated by the controller. Calling
    # `delegate_to_rack_app!` aborts execution of the current
    # controller action and returns the response of the given Rack app
    # instead.
    #
    # The second argument passed to `throw` is becomes the return
    # value of `catch`. If `throw` is not called, `catch` passes the
    # return value of its block.
    #
    # [1] https://github.com/rails/rails/blob/8bec77cc0f1fd47677a331a64f68c5918efd2ca9/actionpack/lib/action_controller/metal.rb#L188
    def dispatch(*)
      catch(:delegate) { super }
    end
  end
end
