Class: Jsapi::Controller::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/jsapi/controller/response.rb

Overview

Used to jsonify a response.

Defined Under Namespace

Classes: JsonifyError

Instance Method Summary collapse

Constructor Details

#initialize(object, response, definitions, omit: nil) ⇒ Response

Creates a new instance to jsonify object according to response. References are resolved to API components in definitions.

The :omit option specifies on which conditions properties are omitted. Possible values are:

  • :empty - All of the properties whose value is empty are omitted.

  • :nil - All of the properties whose value is nil are omitted.

Raises an ArgumentError when :omit is other than :empty, :nil or nil.



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/jsapi/controller/response.rb', line 28

def initialize(object, response, definitions, omit: nil)
  @object = object
  @response = response
  @definitions = definitions

  @omittable_check =
    case omit
    when nil
      nil
    when :nil
      ->(value, schema) { schema.omittable? && value.nil? }
    when :empty
      ->(value, schema) { schema.omittable? && value.try(:empty?) }
    else
      raise InvalidArgumentError.new('omit', omit, valid_values: %i[empty nil])
    end
end

Instance Method Details

#inspectObject

:nodoc:



46
47
48
# File 'lib/jsapi/controller/response.rb', line 46

def inspect # :nodoc:
  "#<#{self.class.name} #{@object.inspect}>"
end

#to_jsonObject

Returns the JSON representation of the response as a string.



51
52
53
54
55
56
57
58
# File 'lib/jsapi/controller/response.rb', line 51

def to_json(*)
  schema = @response.schema.resolve(@definitions)
  if @response.locale
    I18n.with_locale(@response.locale) { jsonify(@object, schema) }
  else
    jsonify(@object, schema)
  end.to_json
end