Class: Halibut::Core::RelationMap
- Inherits:
-
Object
- Object
- Halibut::Core::RelationMap
- 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
-
#add(relation, item) ⇒ Object
Adds an object to a relation.
-
#initialize(options = {}) ⇒ RelationMap
constructor
A new instance of RelationMap.
-
#single_item_arrays? ⇒ Boolean
Returns true if the relation map is configured to always to permit single arrays when to_hash is called.
-
#to_hash ⇒ Hash
Returns a hash corresponding to the object.
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( = {}) @relations = {} @options = DEFAULT_OPTIONS.merge() end |
Instance Method Details
#add(relation, item) ⇒ Object
Adds an object to a relation.
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>>]
30 31 32 33 34 35 36 |
# File 'lib/halibut/core/relation_map.rb', line 30 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
60 61 62 |
# File 'lib/halibut/core/relation_map.rb', line 60 def single_item_arrays? @options[:single_item_arrays] end |
#to_hash ⇒ Hash
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.
44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/halibut/core/relation_map.rb', line 44 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 |