Module: Philiprehberger::HeaderKit::Link

Defined in:
lib/philiprehberger/header_kit/link.rb

Overview

Parses and builds RFC 8288 Link header values.

Each link entry contains a URI and optional parameters such as rel, type, and title.

Constant Summary collapse

URI_PATTERN =
/<([^>]*)>/

Class Method Summary collapse

Class Method Details

.build(links) ⇒ String

Build a Link header string from an array of link hashes.

Parameters:

  • links (Array<Hash>)

    each with :uri and optional :rel, :type, :title

Returns:

  • (String)

    formatted Link header value



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/philiprehberger/header_kit/link.rb', line 25

def self.build(links)
  return '' if links.nil? || links.empty?

  parts = links.map do |link|
    entry = "<#{link[:uri]}>"
    entry += "; rel=\"#{link[:rel]}\"" if link[:rel]
    entry += "; type=\"#{link[:type]}\"" if link[:type]
    entry += "; title=\"#{link[:title]}\"" if link[:title]
    entry
  end

  parts.join(', ')
end

.parse(header) ⇒ Array<Hash>

Parse a Link header string into an array of link entries.

Parameters:

  • header (String)

    the Link header value

Returns:

  • (Array<Hash>)

    each with :uri, :rel, :type, :title keys



15
16
17
18
19
# File 'lib/philiprehberger/header_kit/link.rb', line 15

def self.parse(header)
  return [] if header.nil? || header.strip.empty?

  header.split(/,(?=\s*<)/).map { |entry| parse_entry(entry.strip) }.compact
end