Class: Discodactyl::LinkHeader

Inherits:
Hash
  • Object
show all
Defined in:
lib/discodactyl/link_header.rb

Overview

Access to web links stored in HTTP Link header-fields. See also: tools.ietf.org/html/draft-nottingham-http-link-header

Class Method Summary collapse

Class Method Details

.parse(string) ⇒ Object

Take the link header value as a string and parse it into a Hash

For example, the raw link header

Link: </>; rel="http://example.net/foo"

is parsed by saying

link = LinkHeader.parse('</>; rel="http://example.net/foo"')
link[:href] # '/'
link[:rel] # ['http://example.net/foo']

16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/discodactyl/link_header.rb', line 16

def parse(string)
  LinkHeader.new.tap do |params|
    if string =~ /^<([^>]+)>(.*)$/
      params[:href] = $1
      $2.split(/;\s*/).each do |part|
        param, value = part.split '='
        value = value[1...-1] if value =~ /^".*"$/
        if param =~ /rel/i
            insert_name_into_hash(params, param.to_sym, value)
        elsif !param.nil?
            params[param.to_sym] = value
        end
      end
    else
      raise "malformed link header: #{string}"
    end
  end
end