Class: Core::Service::Response

Inherits:
Object
  • Object
show all
Extended by:
Initializable
Includes:
Benchmarking, References
Defined in:
app/api/core/service.rb

Overview

A response from an endpoint handler is made of a pair of values. One is the object that is to be sent back to the client in JSON. The other is the endpoint handler that dealt with the request and that provides the actions that are available for said object. So the JSON that is actually returned is a merge of the object JSON and the actions.

Defined Under Namespace

Classes: Initializer

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Initializable

extended, initialized_attr_reader, initialized_delegate

Methods included from Benchmarking

#benchmark, registered

Constructor Details

#initialize(request, &block) ⇒ Response

Returns a new instance of Response.


219
220
221
222
223
# File 'app/api/core/service.rb', line 219

def initialize(request, &block)
  @request, @io, @include_actions = request, nil, true
  status(200)
  super(&block)
end

Instance Attribute Details

#requestObject (readonly)

Returns the value of attribute request.


207
208
209
# File 'app/api/core/service.rb', line 207

def request
  @request
end

Instance Method Details

#closeObject

rubocop:enable Metrics/MethodLength


250
251
252
253
254
255
# File 'app/api/core/service.rb', line 250

def close
  identifier, started_at = self.identifier, self.started_at # Save for later as next line discards our request!
  discard_all_references
ensure
  Rails.logger.info("API[finished]: #{identifier} in #{Time.zone.now - started_at}s")
end

#each(&block) ⇒ Object

– Note that this method disables garbage collection, which should improve the performance of writing out the JSON to the client. The garbage collection is then re-enabled in close. ++ rubocop:todo Metrics/MethodLength


230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'app/api/core/service.rb', line 230

def each(&block) # rubocop:todo Metrics/AbcSize
  Rails.logger.info('API[streaming]: starting JSON streaming')
  start = Time.zone.now

  ::Core::Io::Buffer.new(block) do |buffer|
    ::Core::Io::Json::Stream
      .new(buffer)
      .open do |stream|
        ::Core::Io::Registry
          .instance
          .lookup_for_object(object)
          .as_json(response: self, target: object, stream: stream, object: object, handled_by: handled_by)
      end
  end

  Rails.logger.info("API[streaming]: finished JSON streaming in #{Time.zone.now - start}s")
end