Skip to content

Instantly share code, notes, and snippets.

@thesowah
Last active Jul 30, 2021
Embed
What would you like to do?
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

eduardoprentcomau commented Nov 22, 2019

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