Sha256: f883b6d6b6ab157d90a98656035dfec0b03848e66cb5868c6ea5d49064e3b5f5

Contents?: true

Size: 1.5 KB

Versions: 7

Compression:

Stored size: 1.5 KB

Contents

module JsonapiCompliable
  module Stats
    # 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 } } }
    #   }
    class Payload
      # @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
      def initialize(resource, query_hash, scope)
        @resource   = resource
        @query_hash = query_hash[:stats]
        @scope      = scope
      end

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

      def each_calculation(name, calculations)
        calculations.each do |calc|
          function = @resource.stat(name, calc)
          yield calc, function
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
jsonapi_compliable-0.11.34 lib/jsonapi_compliable/stats/payload.rb
jsonapi_compliable-0.11.33 lib/jsonapi_compliable/stats/payload.rb
jsonapi_compliable-0.11.32 lib/jsonapi_compliable/stats/payload.rb
jsonapi_compliable-0.11.31 lib/jsonapi_compliable/stats/payload.rb
jsonapi_compliable-0.11.30 lib/jsonapi_compliable/stats/payload.rb
jsonapi_compliable-0.11.29 lib/jsonapi_compliable/stats/payload.rb
jsonapi_compliable-0.11.28 lib/jsonapi_compliable/stats/payload.rb