class JsonapiCompliable::Stats::Payload

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 } } }
}

Public Class Methods

new(resource, query_hash, scope) click to toggle source

@param [Resource] resource the resource instance @param [Hash] query_hash the Query#to_hash for the current resource @param scope the scope we are chaining/modifying

# 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

Public Instance Methods

generate() click to toggle source

Generate the payload for +{ meta: { stats: { … } } }+ Loops over all calculations, computes then, and gives back a hash of stats and their results. @return [Hash] the generated payload

# 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|
        args = function.arity == 3 ? [@scope, name, @resource] : [@scope, name]
        stats[name][calc] = function.call(*args)
      end
    end
  end
end

Private Instance Methods

each_calculation(name, calculations) { |calc, function| ... } click to toggle source
# File lib/jsonapi_compliable/stats/payload.rb, line 45
def each_calculation(name, calculations)
  calculations.each do |calc|
    function = @resource.stat(name, calc)
    yield calc, function
  end
end