Sha256: deabe32f8744efc8a4f418c527b24b5d53cb57c0dc07569ac7699440816d7747

Contents?: true

Size: 1.39 KB

Versions: 43

Compression:

Stored size: 1.39 KB

Contents

module RestPack::Serializer
  class Result
    attr_accessor :resources, :meta, :links

    def initialize
      @resources = {}
      @meta = {}
      @links = {}
    end

    def serialize
      result = {}

      unless @resources.empty?
        inject_has_many_links!
        result[@resources.keys.first] = @resources.values.first

        linked = @resources.except(@resources.keys.first)
        result[:linked] = linked unless linked.empty?
      end

      result[:links] = @links unless @links.empty?
      result[:meta] = @meta unless @meta.empty?

      result
    end

    private

    def inject_has_many_links!
      @resources.keys.each do |key|
        @resources[key].each do |item|
          if item[:links]
            item[:links].each do |link_key, link_value|
              unless link_value.is_a? Array
                plural_linked_key = "#{link_key}s".to_sym

                if @resources[plural_linked_key]
                  linked_resource = @resources[plural_linked_key].find { |i| i[:id] == link_value }
                  if linked_resource
                    linked_resource[:links] ||= {}
                    linked_resource[:links][key] ||= []
                    linked_resource[:links][key] << item[:id]
                    linked_resource[:links][key].uniq!
                  end
                end
              end
            end
          end
        end
      end
    end
  end
end

Version data entries

43 entries across 43 versions & 1 rubygems

Version Path
restpack_serializer-0.6.15 lib/restpack_serializer/result.rb
restpack_serializer-0.6.14 lib/restpack_serializer/result.rb
restpack_serializer-0.6.13 lib/restpack_serializer/result.rb
restpack_serializer-0.6.12 lib/restpack_serializer/result.rb
restpack_serializer-0.6.11 lib/restpack_serializer/result.rb
restpack_serializer-0.6.10 lib/restpack_serializer/result.rb
restpack_serializer-0.6.9 lib/restpack_serializer/result.rb
restpack_serializer-0.6.8 lib/restpack_serializer/result.rb
restpack_serializer-0.6.7 lib/restpack_serializer/result.rb
restpack_serializer-0.6.6 lib/restpack_serializer/result.rb
restpack_serializer-0.6.5 lib/restpack_serializer/result.rb
restpack_serializer-0.6.4 lib/restpack_serializer/result.rb
restpack_serializer-0.6.3 lib/restpack_serializer/result.rb
restpack_serializer-0.6.2 lib/restpack_serializer/result.rb
restpack_serializer-0.6.1 lib/restpack_serializer/result.rb
restpack_serializer-0.5.10 lib/restpack_serializer/result.rb
restpack_serializer-0.5.9 lib/restpack_serializer/result.rb
restpack_serializer-0.5.8 lib/restpack_serializer/result.rb
restpack_serializer-0.5.7 lib/restpack_serializer/result.rb
restpack_serializer-0.5.6 lib/restpack_serializer/result.rb