class OneBusAway::Client

Class for establishing a connection to one bus away

Attributes

api_key[RW]
api_method[RW]
base_url[R]
http_response[R]
parameters[RW]
url[R]

Public Class Methods

new(options = {}) click to toggle source
# File lib/one_bus_away/client.rb, line 10
def initialize(options = {})
  @api_method = options[:api_method]
  @api_key = options[:api_key] || apply_local_api_key
  @parameters = options[:parameters]
  @base_url = 'api.pugetsound.onebusaway.org'
end

Public Instance Methods

apply_local_api_key() click to toggle source

Applies ~/.one_bus_away to @api if the file exists otherwise, it fails.

# File lib/one_bus_away/client.rb, line 65
def apply_local_api_key
  if File.exist? ENV['HOME'] + '/.one_bus_away'
    file = File.read(ENV['HOME'] + '/.one_bus_away')
    @api_key = file.chomp
  else
    fail 'no API key provided. Please ensure you have your api key'\
      'installed in here: ~/.one_bus_away'
  end
end
build_path() click to toggle source

Builds the path for utilization in build_url

# File lib/one_bus_away/client.rb, line 49
def build_path
  path = %w(api where)
  path.concat api_method
  path = path.join('/')
  @path = "/#{path}.json"
end
build_query() click to toggle source

Build query for utilization in build_url

# File lib/one_bus_away/client.rb, line 57
def build_query
  query = { key: @api_key }
  query.merge! @parameters if @parameters
  query.map { |k, v| "#{k}=#{v}" }.join('&')
end
build_url() click to toggle source

Builds a valid url, then sets this string to @url

# File lib/one_bus_away/client.rb, line 40
def build_url
  @url = URI::HTTP.build(
    host: @base_url,
    path: build_path,
    query: build_query
  ).to_s if valid?
end
get() click to toggle source

Provided that @url is set, HTTP get @url

# File lib/one_bus_away/client.rb, line 27
def get
  if @url
    response = RestClient.get(@url)
    json = JSON.parse(response)
    @http_response = RecursiveOpenStruct.new(
      json, recurse_over_arrays: true
    )
  else
    fail 'url is not properly built'
  end
end
valid?() click to toggle source

Verifies that @api_method and @api_key are set

# File lib/one_bus_away/client.rb, line 18
def valid?
  if api_method && api_key
    true
  else
    false
  end
end