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: HashReader, JsonifyError
Instance Method Summary collapse
-
#initialize(object, content_model, omit: nil, locale: nil) ⇒ Response
constructor
Creates a new instance to jsonify
objectaccording tocontent_model. -
#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, content_model, omit: nil, locale: nil) ⇒ Response
Creates a new instance to jsonify object according to content_model.
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.
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/jsapi/controller/response.rb', line 54 def initialize(object, content_model, omit: nil, locale: nil) @object = object @content_model = content_model @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 ArgumentError, Messages.invalid_value( name: 'omit', value: omit, valid_values: %i[empty nil] ) end @locale = locale end |
Instance Method Details
#inspect ⇒ Object
:nodoc:
77 78 79 |
# File 'lib/jsapi/controller/response.rb', line 77 def inspect # :nodoc: "#<#{self.class.name} #{@object.inspect}>" end |
#to_json ⇒ Object
Returns the JSON representation of the response as a string.
82 83 84 |
# File 'lib/jsapi/controller/response.rb', line 82 def to_json(*) with_locale { jsonify(@object, @content_model.schema) }.to_json end |
#write_json_seq_to(stream) ⇒ Object
Writes the response in JSON sequence text format to stream.
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
# File 'lib/jsapi/controller/response.rb', line 87 def write_json_seq_to(stream) schema = @content_model.schema with_locale do items, item_schema = if schema.array? && @object.respond_to?(:each) [@object, schema.items] 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 |