Module: Webhookdb::Service::Collection::Helpers

Included in:
Helpers
Defined in:
lib/webhookdb/service/collection.rb

Instance Method Summary collapse

Instance Method Details

#present_collection(collection, opts = {}) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/webhookdb/service/collection.rb', line 50

def present_collection(collection, opts={})
  item_entity = opts.delete(:with) || opts.delete(:using)
  if !item_entity.nil? && (item_entity < Webhookdb::Service::Entities::Base)
    # If we have a real entity, we only want message on the top level, not any nested
    item_entity = Class.new(item_entity) do
      unexpose :message
    end
  end
  unless (collection_entity = Webhookdb::Service::Collection.collection_entity_cache[item_entity])
    collection_entity = Class.new(Webhookdb::Service::Entities::Base) do
      define_method(:object_type) do
        "list"
      end
      expose :items, using: item_entity
      expose :current_page
      expose :page_count
      expose :total_count
      expose :more?, as: :has_more
      expose :message do |_instance, options|
        options[:message] || ""
      end
      expose :display_headers do |_, _|
        item_entity.respond_to?(:display_headers) ? item_entity.send(:display_headers) : []
      end
    end
    Webhookdb::Service::Collection.collection_entity_cache[item_entity] = collection_entity
  end
  opts[:with] = collection_entity

  wrapped =
    if collection.respond_to?(:dataset) || collection.is_a?(Sequel::Dataset)
      Webhookdb::Service::Collection.from_dataset(collection)
    elsif collection.is_a?(Webhookdb::Service::Collection)
      collection
    else
      Webhookdb::Service::Collection.from_array(collection)
    end

  present wrapped, opts
end