collection_serializer.rb 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # frozen_string_literal: true
  2. class ActivityPub::CollectionSerializer < ActivityPub::Serializer
  3. class StringSerializer < ActiveModel::Serializer
  4. # Despite the name, it does not return a hash, but the same can be said of
  5. # the ActiveModel::Serializer::CollectionSerializer class which handles
  6. # arrays.
  7. def serializable_hash(*_args)
  8. object
  9. end
  10. end
  11. def self.serializer_for(model, options)
  12. case model.class.name
  13. when 'Status'
  14. ActivityPub::NoteSerializer
  15. when 'Device'
  16. ActivityPub::DeviceSerializer
  17. when 'FeaturedTag'
  18. ActivityPub::HashtagSerializer
  19. when 'ActivityPub::CollectionPresenter'
  20. ActivityPub::CollectionSerializer
  21. when 'String'
  22. StringSerializer
  23. else
  24. super
  25. end
  26. end
  27. attribute :id, if: -> { object.id.present? }
  28. attribute :type
  29. attribute :total_items, if: -> { object.size.present? }
  30. attribute :next, if: -> { object.next.present? }
  31. attribute :prev, if: -> { object.prev.present? }
  32. attribute :part_of, if: -> { object.part_of.present? }
  33. has_one :first, if: -> { object.first.present? }
  34. has_one :last, if: -> { object.last.present? }
  35. has_many :items, key: :items, if: -> { (!object.items.nil? || page?) && !ordered? }
  36. has_many :items, key: :ordered_items, if: -> { (!object.items.nil? || page?) && ordered? }
  37. def type
  38. if page?
  39. ordered? ? 'OrderedCollectionPage' : 'CollectionPage'
  40. else
  41. ordered? ? 'OrderedCollection' : 'Collection'
  42. end
  43. end
  44. def total_items
  45. object.size
  46. end
  47. private
  48. def ordered?
  49. object.type == :ordered
  50. end
  51. def page?
  52. object.part_of.present? || object.page.present?
  53. end
  54. end