Module: Roar::JSON::HAL::Resources::ToHashExt

Included in:
Roar::JSON::HAL::Resources
Defined in:
lib/eipiai/representers/ext/roar/hal.rb

Overview

ToHashExt

Adds a superset of functions on top of the default ‘Roar::JSON::HAL::Resources#to_hash`.

Instance Method Summary collapse

Instance Method Details

#to_hashHash Also known as: to_h

to_hash

taps into the default ‘Roar::JSON::HAL::Resources#to_hash` and adds `curies` links to the hash, if a curied object is present.

The configuration value ‘curie_uris` needs to be defined, and be a hash of `{ curie => url }`. If your links contains a key `b:items`, then the curie link will be taken from the `curie_uris` hash, with key matching `b`:

Eipiai.configuration.curie_uris = { b: 'https://example.com/' }

‘_links` key `b:items` will result in a curie pointing to the above address.

Examples:

post('/items', '{ "uid": "hello" }', 'Content-Type': 'application/json')
items = Struct.new(:dataset).new(Item.dataset)
Eipiai.configuration.curie_uris = { b: 'https://example.com/{rel}' }

ItemsRepresenter.new(items).to_hash['_links']['curies']
  # => [{ name: "b", href: "https://example.com/{rel}", templated: true }]

Returns:

  • (Hash)

    hash representation of the represented object



41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/eipiai/representers/ext/roar/hal.rb', line 41

def to_hash(*)
  super.tap do |hash|
    curies = Set.new
    hash.fetch('_links', {}).each do |name, _|
      next unless (curie = name[/^(\S+?):\S+/, 1])
      next unless (curie_href = Eipiai.configuration.curie_uris[curie.to_sym])

      curies.add(name: curie, href: curie_href, templated: true)
    end

    hash['_links']['curies'] = curies.to_a if curies.any?
  end
end