serializer.rb 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. # frozen_string_literal: true
  2. class ActivityPub::Serializer < ActiveModel::Serializer
  3. with_options instance_writer: false, instance_reader: true do |serializer|
  4. serializer.class_attribute :_named_contexts
  5. serializer.class_attribute :_context_extensions
  6. self._named_contexts ||= {}
  7. self._context_extensions ||= {}
  8. end
  9. def self.inherited(base)
  10. super
  11. base._named_contexts = _named_contexts.dup
  12. base._context_extensions = _context_extensions.dup
  13. end
  14. def self.context(*named_contexts)
  15. named_contexts.each do |context|
  16. _named_contexts[context] = true
  17. end
  18. end
  19. def self.context_extensions(*extension_names)
  20. extension_names.each do |extension_name|
  21. _context_extensions[extension_name] = true
  22. end
  23. end
  24. def serializable_hash(adapter_options = nil, options = {}, adapter_instance = self.class.serialization_adapter_instance)
  25. unless adapter_options&.fetch(:named_contexts, nil).nil?
  26. adapter_options[:named_contexts].merge!(_named_contexts)
  27. adapter_options[:context_extensions].merge!(_context_extensions)
  28. end
  29. super(adapter_options, options, adapter_instance)
  30. end
  31. end