Skip to content

Instantly share code, notes, and snippets.

@thesowah
Last active July 30, 2021 18:02
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thesowah/0ca5e1b4b3c61bfe8e13 to your computer and use it in GitHub Desktop.
Save thesowah/0ca5e1b4b3c61bfe8e13 to your computer and use it in GitHub Desktop.
Parse link headers from Github API in Ruby
require 'rest_client'
class Plh
def self.parse_link_header(url, params={})
response = RestClient.get url, params
links = Hash.new
parts = response.headers[:link].split(',')
# Parse each part into a named link
parts.each do |part, index|
section = part.split(';')
url = section[0][/<(.*)>/,1]
name = section[1][/rel="(.*)"/,1].to_sym
links[name] = url
end
return links
end
end
@eduardoprentcomau
Copy link

Thanks! A small variation suggestion:

def self.parse_link_header(url, params={})
  response = RestClient.get url, params
  parts = response.headers[:link].split(',')

  parts.map do |part, _|
    section = part.split(';')
    name = section[1][/rel="(.*)"/, 1].to_sym
    url = section[0][/<(.*)>/, 1]
    results = section[2][/results="(.*)"/, 1] == 'true'

    [name, url: url, results: results]
  end.to_h
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment