Sha256: 2bad4cc3fcdd305ff5d3760c99c59bf2da134c34c4007271f6251afd0c16d48c

Contents?: true

Size: 1.43 KB

Versions: 6

Compression:

Stored size: 1.43 KB

Contents

require 'rack'
require 'dragonfly/utils'
require 'dragonfly/response'

module Dragonfly
  class RoutedEndpoint

    class NoRoutingParams < RuntimeError; end

    def initialize(app, &block)
      @app = app
      @block = block
    end

    def call(env)
      params = Utils.symbolize_keys Rack::Request.new(env).params
      value = @block.call(params.merge(routing_params(env)), @app, env)
      case value
      when nil then plain_response(404, "Not Found")
      when Job, Model::Attachment
        job = value.is_a?(Model::Attachment) ? value.job : value
        Response.new(job, env).to_response
      else
        Dragonfly.warn("can't handle return value from routed endpoint: #{value.inspect}")
        plain_response(500, "Server Error")
      end
    rescue Job::NoSHAGiven
      plain_response(400, "You need to give a SHA parameter")
    rescue Job::IncorrectSHA
      plain_response(400, "The SHA parameter you gave is incorrect")
    end

    def inspect
      "<#{self.class.name} for app #{@app.name.inspect} >"
    end

    private

    def routing_params(env)
      env['rack.routing_args'] ||
        env['action_dispatch.request.path_parameters'] ||
        env['router.params'] ||
        env['dragonfly.params'] ||
        raise(NoRoutingParams, "couldn't find any routing parameters in env #{env.inspect}")
    end

    def plain_response(status, message)
      [status, {"Content-Type" => "text/plain"}, [message]]
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
dragonfly-1.4.0 lib/dragonfly/routed_endpoint.rb
dragonfly-1.3.0 lib/dragonfly/routed_endpoint.rb
dragonfly-1.2.1 lib/dragonfly/routed_endpoint.rb
dragonfly-1.2.0 lib/dragonfly/routed_endpoint.rb
dragonfly-1.1.5 lib/dragonfly/routed_endpoint.rb
dragonfly-1.1.4 lib/dragonfly/routed_endpoint.rb