Class: Jsapi::Controller::Response
- Inherits:
-
Object
- Object
- Jsapi::Controller::Response
- Defined in:
- lib/jsapi/controller/response.rb
Overview
Used to jsonify a response.
Defined Under Namespace
Classes: JsonifyError
Instance Method Summary collapse
-
#initialize(object, response, definitions, omit: nil) ⇒ Response
constructor
Creates a new instance to jsonify
objectaccording toresponse. -
#inspect ⇒ Object
:nodoc:.
-
#to_json ⇒ Object
Returns the JSON representation of the response as a string.
-
#write_json_seq_to(stream) ⇒ Object
Writes the response in JSON sequence text format to
stream.
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 isnilare 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
#inspect ⇒ Object
:nodoc:
46 47 48 |
# File 'lib/jsapi/controller/response.rb', line 46 def inspect # :nodoc: "#<#{self.class.name} #{@object.inspect}>" end |
#to_json ⇒ Object
Returns the JSON representation of the response as a string.
51 52 53 54 |
# File 'lib/jsapi/controller/response.rb', line 51 def to_json(*) schema = @response.schema.resolve(@definitions) with_locale { jsonify(@object, schema) }.to_json end |
#write_json_seq_to(stream) ⇒ Object
Writes the response in JSON sequence text format to stream.
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/jsapi/controller/response.rb', line 57 def write_json_seq_to(stream) schema = @response.schema.resolve(@definitions) with_locale do items, item_schema = if schema.array? && @object.respond_to?(:each) [@object, schema.items.resolve(@definitions)] else [[@object], schema] end items.each do |item| stream.write("\u001E") # Record separator (see RFC 7464) stream.write(jsonify(item, item_schema).to_json) stream.write("\n") end end nil end |