Class: HyperResource::Links

Inherits:
Hash
  • Object
show all
Defined in:
lib/hyper_resource/links.rb

Overview

HyperResource::Links is a modified Hash that permits lookup of a link by its link relation (rel), or an abbreviation thereof. It also provides read access through ‘method_missing`. It is typically created by HyperResource, not by end users.

For example, a link with rel ‘someapi:widgets` is accessible by any of `self.widgets`, `self`, `self`, and `self.

Instance Method Summary collapse

Constructor Details

#initialize(resource = nil) ⇒ Links

Returns a new instance of Links.



14
15
16
# File 'lib/hyper_resource/links.rb', line 14

def initialize(resource=nil)
  ## We used to store the resource, but we didn't need to.  Now we don't.
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object

Provides links.somelink(:a => b) to links.somelink.where(:a => b) expansion.



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/hyper_resource/links.rb', line 50

def method_missing(method, *args)
  unless self[method]
    raise NoMethodError, "undefined method `#{method}' for #{self.inspect}"
  end

  if args.count > 0
    self[method].where(*args)
  else
    self[method]
  end
end

Instance Method Details

#[](rel) ⇒ Object

Retrieves a link by its rel.



43
44
45
# File 'lib/hyper_resource/links.rb', line 43

def [](rel)
  super(rel.to_s)
end

#[]=(rel, link) ⇒ Object

Stores a link for future retrieval by its link rel or abbreviations thereof.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/hyper_resource/links.rb', line 20

def []=(rel, link)
  rel = rel.to_s

  ## Every link must appear under its literal name.
  names = [rel]

  ## Extract 'foo' from e.g. 'http://example.com/foo',
  ## 'http://example.com/url#foo', 'somecurie:foo'.
  if m=rel.match(%r{[:/#](.+)})
    names << m[1]
  end

  ## Underscore all non-word characters.
  underscored_names = names.map{|n| n.gsub(/[^a-zA-Z_]/, '_')}
  names = (names + underscored_names).uniq

  ## Register this link under every name we've come up with.
  names.each do |name|
    super(name, link)
  end
end

#respond_to?(method, *args) ⇒ Boolean

Returns:

  • (Boolean)


63
64
65
66
# File 'lib/hyper_resource/links.rb', line 63

def respond_to?(method, *args)
  return true if self.has_key?(method.to_s)
  super
end