module Pragma::Decorator::Collection

This module is used to represent collections of objects.

It will wrap the collection in a data property so that you can include meta-data about the collection at the root level.

@example Using Collection to include a total count

class ArticlesDecorator < Pragma::Decorator::Base
  include Pragma::Decorator::Collection

  property :total_count, exec_context: :decorator

  def total_count
    represented.count
  end
end

# {
#   "data": [
#     { "...": "..." },
#     { "...": "..." },
#     { "...": "..." }
#   ],
#   "total_count": 150
# }
ArticlesDecorator.new(Article.all).to_hash

Public Class Methods

included(klass) click to toggle source
# File lib/pragma/decorator/collection.rb, line 31
def self.included(klass)
  klass.include InstanceMethods
  klass.extend ClassMethods

  klass.class_eval do
    collection :data, exec_context: :decorator, getter: (lambda do |options:, **|
      represented_collection = if self.class.instance_decorator.is_a?(Proc)
        represented.map do |item|
          self.class.instance_decorator.call(item).represent(item).to_hash(options)
        end
      elsif self.class.instance_decorator
        self.class.instance_decorator.represent(represented.to_a).to_hash(options)
      else
        represented
      end
      represented_collection
    end)
  end
end