Sha256: 64efd80090d274276f67458adf371fe1733ba657787159137546677867a1223c

Contents?: true

Size: 1 KB

Versions: 1

Compression:

Stored size: 1 KB

Contents

require 'json'
require 'rack'

module RailsCloudTasks
  module Rack
    class Jobs
      class << self
        def call(env)
          job_class = extract_job_class(env)

          request = ::Rack::Request.new(env)
          job_args = extract_args(request)
          job_class.perform_now(job_args)

          response(200, {})
        rescue Rack::InvalidPayloadError => e
          response(422, { error: e.message })
        rescue StandardError => e
          response(500, { error: e.message })
        end

        private

        def extract_job_class(env)
          env.dig('action_dispatch.request.path_parameters', :job_class)
             .constantize
        end

        def extract_args(request)
          body = request.body.read
          JSON.parse(body)
        rescue JSON::ParserError, KeyError
          raise Rack::InvalidPayloadError
        end

        def response(status, body)
          [status, { 'Content-Type' => 'application/json' }, [body.to_json]]
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rails-cloud-tasks-0.0.2 lib/rails_cloud_tasks/rack/jobs.rb