Class: JsonapiCompliable::Stats::Payload

Inherits:
Object
  • Object
show all
Defined in:
lib/jsonapi_compliable/stats/payload.rb

Overview

Generate the stats payload so we can return it in the response.

{
  data: [...],
  meta: { stats: the_generated_payload }
}

For example:

{
  data: [...],
  meta: { stats: { total: { count: 100 } } }
}

Instance Method Summary collapse

Constructor Details

#initialize(resource, query_hash, scope) ⇒ Payload

Returns a new instance of Payload

Parameters:

  • resource (Resource)

    the resource instance

  • query_hash (Hash)

    the Query#to_hash for the current resource

  • scope

    the scope we are chaining/modifying



20
21
22
23
24
# File 'lib/jsonapi_compliable/stats/payload.rb', line 20

def initialize(resource, query_hash, scope)
  @resource   = resource
  @query_hash = query_hash[:stats]
  @scope      = scope
end

Instance Method Details

#generateHash

Generate the payload for { meta: { stats: { … } } } Loops over all calculations, computes then, and gives back a hash of stats and their results.

Returns:

  • (Hash)

    the generated payload



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/jsonapi_compliable/stats/payload.rb', line 30

def generate
  {}.tap do |stats|
    @query_hash.each_pair do |name, calculation|
      stats[name] = {}

      each_calculation(name, calculation) do |calc, function|
        stats[name][calc] = function.call(@scope, name)
      end
    end
  end
end