Class: Yaks::Reader::Hal

Inherits:
Object
  • Object
show all
Includes:
Util
Defined in:
lib/yaks/reader/hal.rb

Instance Method Summary collapse

Methods included from Util

#Resolve, #camelize, #extract_options, #reject_keys, #slice_hash, #symbolize_keys, #underscore

Instance Method Details

#array(x) ⇒ Object



35
36
37
# File 'lib/yaks/reader/hal.rb', line 35

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

#call(parsed_json, _env = {}) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/yaks/reader/hal.rb', line 6

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

#convert_embedded(embedded) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/yaks/reader/hal.rb', line 39

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


24
25
26
27
28
29
30
31
32
33
# File 'lib/yaks/reader/hal.rb', line 24

def convert_links(links)
  links.flat_map do |rel, link|
    array(link).map do |l|
      options = symbolize_keys(slice_hash(l, 'title', 'templated'))
      # if it looks like a keyword we'll assume it's a registered rel type
      rel = rel.to_sym if rel =~ /\A\w+\z/
      Resource::Link.new(rel: rel, uri: l['href'], options: options)
    end
  end
end


19
20
21
22
# File 'lib/yaks/reader/hal.rb', line 19

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