Sha256: 2b209d490549a9226115851712c158a05c884fab9dfbdc83f2b06357a2aa0f19

Contents?: true

Size: 1.66 KB

Versions: 7

Compression:

Stored size: 1.66 KB

Contents

module Yaks
  module Reader
    class Hal

      def call(parsed_json, env = {})
        attributes = parsed_json.dup
        links      = convert_links(attributes.delete('_links') || {})
        embedded   = convert_embedded(attributes.delete('_embedded') || {})


        Resource.new(
          type: attributes.delete('type') || type_from_links(links),
          attributes: Util.symbolize_keys(attributes),
          links: links,
          subresources: embedded
        )
      end

      def type_from_links(links)
        profile = links.detect {|l| l.rel?(:profile)}
        profile.uri[/\w+$/] if profile
      end

      def convert_links(links)
        Set[*
            links.flat_map do |rel, link|
              array(link).map do |l|
                options = Util.symbolize_keys(Util.slice_hash(l, 'title', 'templated'))
                rel = rel.to_sym if Yaks::Identifier::LinkRelation.iana?(rel)
                Resource::Link.new(rel: rel, uri: l['href'], options: options)
              end
            end
           ]
      end

      def array(x)
        x.instance_of?(Array) ? x : [x]
      end


      def convert_embedded(embedded)
        embedded.flat_map do |rel, resource|
          case resource
          when nil
            NullResource.new
          when Array
            if resource.empty?
              NullResource.new(collection: true)
            else
              CollectionResource.new(
                members: resource.map { |r|
                  call(r).with(type: Util.singularize(rel[/\w+$/])) }
              )
            end
          else
            call(resource)
          end.with(rels: [rel])
        end
      end

    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
yaks-0.8.3 lib/yaks/reader/hal.rb
yaks-0.8.2 lib/yaks/reader/hal.rb
yaks-0.8.1 lib/yaks/reader/hal.rb
yaks-0.8.0 lib/yaks/reader/hal.rb
yaks-0.8.0.beta2 lib/yaks/reader/hal.rb
yaks-0.8.0.beta1 lib/yaks/reader/hal.rb
yaks-0.8.0.alpha lib/yaks/reader/hal.rb