Sha256: fd17517849787bfa4d98f24fcc7cfb619615ad43b88e28a22cb2fd79aad4a4ad

Contents?: true

Size: 988 Bytes

Versions: 1

Compression:

Stored size: 988 Bytes

Contents

# frozen_string_literal: true

require 'json'
require 'rack/utils'

# An object representing RFC 7807 Problem Details
module ProblemDetails
  # The class that implements a Problem Details JSON object described in RFC 7807.
  class Document
    attr_accessor :type, :title, :status, :detail, :instance

    def initialize(params = {})
      params = params.dup
      @type = params.delete(:type)
      @status = Rack::Utils.status_code(params.delete(:status)) if params.key?(:status)
      @title = params.delete(:title) || (@status ? ::Rack::Utils::HTTP_STATUS_CODES[@status] : nil)
      @detail = params.delete(:detail)
      @instance = params.delete(:instance)
      @extentions = params
    end

    def to_hash
      h = {}
      %i[type title status detail instance].each do |key|
        value = public_send(key)
        h[key] = value if value
      end
      h.merge(@extentions)
    end
    alias_method :to_h, :to_hash

    def to_json
      to_hash.to_json
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
problem_details-0.2.3 lib/problem_details/document.rb