lib/jsonapi/resource_serializer.rb in jsonapi-resources-0.0.12 vs lib/jsonapi/resource_serializer.rb in jsonapi-resources-0.0.13

- old
+ new

@@ -1,39 +1,35 @@ module JSONAPI class ResourceSerializer + def initialize(primary_resource_klass) + @primary_resource_klass = primary_resource_klass + @primary_class_name = @primary_resource_klass._type + end + # Converts a single resource, or an array of resources to a hash, conforming to the JSONAPI structure # include: # Purpose: determines which objects will be side loaded with the source objects in a linked section # Example: ['comments','author','comments.tags','author.posts'] # fields: # Purpose: determines which fields are serialized for a resource type. This encompasses both attributes and # association ids in the links section for a resource. Fields are global for a resource type. # Example: { people: [:id, :email, :comments], posts: [:id, :title, :author], comments: [:id, :body, :post]} def serialize_to_hash(source, options = {}) is_resource_collection = source.respond_to?(:to_ary) - return {} if source.nil? || (is_resource_collection && source.size == 0) @fields = options.fetch(:fields, {}) include = options.fetch(:include, []) @key_formatter = options.fetch(:key_formatter, JSONAPI.configuration.key_formatter) @linked_objects = {} requested_associations = parse_includes(include) - if is_resource_collection - @primary_class_name = source[0].class._type - else - @primary_class_name = source.class._type - end - process_primary(source, requested_associations) - primary_class_name = @primary_class_name.to_sym - linked_hash = {} primary_objects = [] @linked_objects.each do |class_name, objects| class_name = class_name.to_sym @@ -47,12 +43,12 @@ end linked_hash[format_key(class_name)] = linked_objects unless linked_objects.empty? end if is_resource_collection - primary_hash = {format_key(primary_class_name) => primary_objects} + primary_hash = {format_key(@primary_class_name) => primary_objects} else - primary_hash = {format_key(primary_class_name) => primary_objects[0]} + primary_hash = {format_key(@primary_class_name) => primary_objects[0]} end if linked_hash.size > 0 primary_hash.merge({linked: linked_hash}) else