Class: Yaks::Mapper::Link

Inherits:
Object
  • Object
show all
Extended by:
Forwardable, Util
Includes:
Util
Defined in:
lib/yaks/mapper/link.rb

Overview

A Yaks::Mapper::Link is part of a mapper’s configuration. It captures what is set through the mapper’s class level ‘#link` function, and is capable of generating a `Yaks::Resource::Link` for a given mapper instance (and hence subject).

It takes a relationship identifier, a URI template and an options hash.

Examples:

link :self, 'http://api.foo.org/users/{id}', title: ->{ "User #{object.name}" }
link :profile, 'http://apidocs.foo.org/profiles/users'
link 'http://apidocs.foo.org/rels/friends', 'http://api.foo.org/users/{id}/friends?page={page}', expand: [:id]

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Util

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

Class Method Details

.create(*args) ⇒ Object



30
31
32
33
# File 'lib/yaks/mapper/link.rb', line 30

def self.create(*args)
  args, options = extract_options(args)
  new(rel: args.first, template: args.last, options: options)
end

Instance Method Details

#add_to_resource(resource, mapper, _context) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/yaks/mapper/link.rb', line 35

def add_to_resource(resource, mapper, _context)
  if options[:remove]
    return resource.with(links: resource.links.reject {|link| link.rel?(rel)})
  end

  resource_link = map_to_resource_link(mapper)
  return resource unless resource_link

  if options[:replace]
    resource.with(links: resource.links.reject {|link| link.rel?(rel)} << resource_link)
  else
    resource.add_link(resource_link)
  end
end


59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/yaks/mapper/link.rb', line 59

def map_to_resource_link(mapper)
  return unless mapper.expand_value(options.fetch(:if, true))

  uri = mapper.expand_uri(template, options.fetch(:expand, true))
  return if uri.nil?

  attrs = {
    rel: rel,
    uri: uri
  }

  resource_link_options(mapper).tap do |opts|
    attrs[:options] = opts unless opts.empty?
  end

  Resource::Link.new(attrs)
end

#rel?(rel) ⇒ Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/yaks/mapper/link.rb', line 50

def rel?(rel)
  rel().eql? rel
end

#templated?Boolean

A link is templated if it does not expand, or only partially

Returns:

  • (Boolean)


55
56
57
# File 'lib/yaks/mapper/link.rb', line 55

def templated?
  !options.fetch(:expand) { true }.equal? true
end