Class: OctocatHerder::Connection

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/octocat_herder/connection.rb

Overview

This implements some additional functionality around HTTParty to help make working with the GitHub API a little nicer.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Connection

If provided a hash of login information, the OctocatHerder::Connection will attempt to make authenticated requests.

If no hash is provided, then unauthenticated requests will be made.

Examples:

Unauthenticated requests

connection = OctocatHerder::Connection.new

Providing an OAuth2 token

connection = OctocatHerder::Connection.new :oauth2_token => 'token'

Providing user name & password

connection = OctocatHerder::Connection.new :user_name => 'user', :password => 'pass'

Parameters:

  • options (Hash<Symbol => String>) (defaults to: {})

    Login information

Options Hash (options):

  • :user_name (String)
  • :password (String)
  • :oauth2_token (String)

Raises:

  • (ArgumentError)

Since:

  • 0.0.1



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/octocat_herder/connection.rb', line 47

def initialize(options={})
  raise ArgumentError.new(
    "OctocatHerder::Connection does not accept: #{options.class}"
  ) unless options.is_a? Hash

  options.keys.each do |k|
    raise ArgumentError.new("Unknown option: '#{k}'") unless [
      :user_name, :password, :oauth2_token
    ].include? k
  end

  if options.keys.include?(:user_name) or options.keys.include?(:password)
    raise ArgumentError.new("When providing :user_name or :password, both are required") unless
      options.keys.include?(:user_name) and options.keys.include?(:password)
  end

  if options.keys.include?(:oauth2_token) and options.keys.include?(:user_name)
    raise ArgumentError.new('Cannot provide both an OAuth2 token, and a user name and password')
  end

  @user_name    = options[:user_name]
  @password     = options[:password]
  @oauth2_token = options[:oauth2_token]

  if oauth2_token
    @httparty_options = { :headers => { 'Authorization' => "token #{oauth2_token}" } }
  elsif user_name
    @httparty_options = { :basic_auth => { :username => user_name, :password => password } }
  end
end

Instance Attribute Details

#oauth2_tokenObject (readonly)

The OAuth2 token to use when doing OAuth2 authentication.

Since:

  • 0.0.1



24
25
26
# File 'lib/octocat_herder/connection.rb', line 24

def oauth2_token
  @oauth2_token
end

#passwordObject (readonly)

Password to use when doing basic HTTP authentication.

Since:

  • 0.0.1



19
20
21
# File 'lib/octocat_herder/connection.rb', line 19

def password
  @password
end

#user_nameObject (readonly)

User name to use when doing basic HTTP authentication.

Since:

  • 0.0.1



14
15
16
# File 'lib/octocat_herder/connection.rb', line 14

def user_name
  @user_name
end

Instance Method Details

#authenticated_requests?true, false

Are we making authenticated requests?

Returns:

  • (true, false)

Since:

  • 0.1.0



138
139
140
141
142
143
144
# File 'lib/octocat_herder/connection.rb', line 138

def authenticated_requests?
  if (user_name and password) or oauth2_token
    true
  else
    false
  end
end

#get(end_point, options = {}) ⇒ Object

Execute a GET request against the GitHub v3 API.

Parameters:

  • end_point (String)

    The part of the API URL after ‘api.github.com’, including the leading ‘/’.

  • options (Hash) (defaults to: {})

    A Hash of options to be passed down to HTTParty, with a couple of extra options.

Options Hash (options):

  • :paginated (true, false)

    Retrieve all pages from a paginated end-point.

  • :params (Hash<String, Symbol => String>)

    Constructed into a query string using #query_string_from_params.

Since:

  • 0.1.0



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/octocat_herder/connection.rb', line 94

def get(end_point, options={})
  paginated = options.delete(:paginated)
  options[:params] ||= {}

  options[:params][:per_page] = 100 if paginated and options[:params][:per_page].nil?

  result = raw_get(end_point, options)
  raise "Unable to retrieve #{end_point}" unless result

  full_result = result.parsed_response

  if paginated
    if next_page = page_from_headers(result.headers, 'next')
      options[:params][:page] = next_page
      options[:paginated]     = true

      full_result += raw_get(end_point, options)
    end
  end

  full_result
end

#page_from_headers(headers, type) ⇒ Object

Retrieve the page number of a given ‘Link:’ header from a hash of HTTP Headers

type can be one of:

next

The immediate next page of results.

last

The last page of first.

first

The first page of results.

prev

The immediate previous page of results.

Parameters:

  • headers (Hash)
  • type ('next', 'last', 'first', 'prev')

Raises:

  • (ArgumentError)

    If type is not one of the allowed values.

Since:

  • 0.1.0



162
163
164
165
166
167
168
169
170
171
# File 'lib/octocat_herder/connection.rb', line 162

def page_from_headers(headers, type)
  raise ArgumentError.new(
    "Unknown type: #{type}"
  ) unless ['next', 'last', 'first', 'prev'].include? type

  link = LinkHeader.parse(headers['link']).find_link(['rel', type])
  return unless link

  CGI.parse(URI.parse(link.href).query)['page'].first
end

#query_string_from_params(params) ⇒ String

Convenience method to generate URL query strings.

Parameters:

  • params (Hash)

    A Hash of key/values to be turned into a URL query string. Does not support nested data.

Returns:

  • (String)

    Empty string if params is an empty hash, otherwise a string of the query parameters with a leading ‘?’.

Since:

  • 0.1.0



183
184
185
186
187
# File 'lib/octocat_herder/connection.rb', line 183

def query_string_from_params(params)
  return '' if params.keys.empty?

  '?' + params.map {|k,v| "#{URI.escape("#{k}")}=#{URI.escape("#{v}")}"}.join('&')
end

#raw_get(end_point, options = {}) ⇒ Object

Small wrapper around HTTParty.get, which handles adding authentication information to the API request.

Since:

  • 0.1.0



121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/octocat_herder/connection.rb', line 121

def raw_get(end_point, options={})
  options = options.dup
  query_params = options.delete(:params) || {}
  query_string = query_string_from_params(query_params)

  request_options = options.merge(httparty_options)
  if httparty_options.has_key?(:headers) and options.has_key(:headers)
    request_options[:headers] = options[:headers].merge(httparty_options[:headers])
  end

  OctocatHerder::Connection.get(end_point + query_string, request_options)
end