Class: Halibut::Core::RelationMap

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/halibut/core/relation_map.rb

Overview

This is an abstract map with behaviour specific to HAL.

spec spec spec

Constant Summary collapse

DEFAULT_OPTIONS =
{ single_item_arrays: false }

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ RelationMap

Returns a new instance of RelationMap


13
14
15
16
# File 'lib/halibut/core/relation_map.rb', line 13

def initialize(options = {})
  @relations = {}
  @options = DEFAULT_OPTIONS.merge(options)
end

Instance Method Details

#add(relation, item) ⇒ Object

Adds an object to a relation.

Examples:

relations = RelationMap.new
relations.add 'self', Link.new('/resource/1')
relations['self']
# => [#<Halibut::Core::Link:0x007fa0ca5b92b8 @href=\"/resource/1\",
     @options=#<Halibut::Core::Link::Options:0x007fa0ca5b9240
     @templated=nil, @type=nil, @name=nil, @profile=nil,
     @title=nil, @hreflang=nil>>]

Parameters:

  • relation (String)

    relation that the object belongs to

  • item (Object)

    the object to add to the relation


31
32
33
34
35
36
37
# File 'lib/halibut/core/relation_map.rb', line 31

def add(relation, item)
  unless item.respond_to?(:to_hash)
    raise ArgumentError.new('only items that can be converted to hashes with #to_hash are permitted')
  end

  @relations[relation] = @relations.fetch(relation, []) << item
end

#single_item_arrays?Boolean

Returns true if the relation map is configured to always to permit single arrays when to_hash is called. The default behavior is to convert single item arrays into instances

Returns:

  • (Boolean)

61
62
63
# File 'lib/halibut/core/relation_map.rb', line 61

def single_item_arrays?
  @options[:single_item_arrays]
end

#to_hashHash

Returns a hash corresponding to the object.

RelationMap doens't just return @relations because it needs to convert correctly when a relation only has a single item.

Returns:

  • (Hash)

    relation map in hash format


45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/halibut/core/relation_map.rb', line 45

def to_hash
  @relations.each_with_object({}) do |(rel,val), obj|
    rel = rel.to_s

    hashed_val = val.map(&:to_hash)
    if val.length == 1 && !single_item_arrays?
      hashed_val = val.first.to_hash
    end

    obj[rel] = hashed_val
  end
end