module JsonapiSerializer::Polymorphic
Public Class Methods
new(opts = {})
click to toggle source
Calls superclass method
JsonapiSerializer::Common::new
# File lib/jsonapi_serializer/polymorphic.rb, line 15 def initialize(opts = {}) super(opts) unless self.class.meta_inherited poly_fields = [*opts.dig(:fields, @type)].map { |f| JsonapiSerializer.key_transform(f) } if self.class.meta_poly.present? @poly = self.class.meta_poly.each_with_object({}) do |poly_class, hash| serializer = poly_class.constantize.new(opts.merge poly_fields: poly_fields) hash[serializer.type] = serializer end else raise "You have to create at least one children serializer for polymorphic #{self.class.name}" end end end
Public Instance Methods
attributes_hash(record)
click to toggle source
# File lib/jsonapi_serializer/polymorphic.rb, line 34 def attributes_hash(record) serializer_for(record).attributes_hash(record) end
id_hash(record)
click to toggle source
# File lib/jsonapi_serializer/polymorphic.rb, line 30 def id_hash(record) serializer_for(record).id_hash(record) end
record_hash(record, context = {})
click to toggle source
# File lib/jsonapi_serializer/polymorphic.rb, line 42 def record_hash(record, context = {}) hash = id_hash(record) attributes = attributes_hash(record) hash[:attributes] = attributes if attributes.present? relationships = relationships_hash(record, context) hash[:relationships] = relationships if relationships.present? hash end
relationships_hash(record, context = {})
click to toggle source
# File lib/jsonapi_serializer/polymorphic.rb, line 38 def relationships_hash(record, context = {}) serializer_for(record).relationships_hash(record, context) end
Private Instance Methods
serializer_for(record)
click to toggle source
# File lib/jsonapi_serializer/polymorphic.rb, line 55 def serializer_for(record) if serializer = @poly[self.class.meta_resolver.call(record)] serializer else raise "Could not resolve serializer for #{record} associated with #{self.class.name}" end end