class TheWalters::Base

A base objet for all endpoints.

Public Class Methods

all(params={}) click to toggle source

Get a list of all.

# File lib/thewalters/base.rb, line 17
def self.all(params={})
  get_all(params)
end

Private Class Methods

base_url() click to toggle source
# File lib/thewalters/base.rb, line 53
def self.base_url; "http://api.thewalters.org" end
faraday() click to toggle source
# File lib/thewalters/base.rb, line 58
def self.faraday
  Faraday.new(
    base_url,
    headers: {:user_agent => "walters-ruby (Faraday v#{Faraday::VERSION})", :accept => 'application/json'}
  ) do |faraday|
    # faraday.response :logger
    faraday.adapter Faraday.default_adapter
  end
end
fetch(path, params={}) click to toggle source
# File lib/thewalters/base.rb, line 68
def self.fetch(path, params={})
  raise "You must first set your api key: try `TheWalters.apikey = '<mykey>'" if TheWalters.apikey.nil?
  params = {:apikey => TheWalters.apikey}.merge(params)
  response = faraday.get(path, params)
  # puts "body: #{response.body}"
  if response.success?
    if response.headers['content-type'] =~ /json/
      parsed = JSON.parse(response.body)
    else
      raise ApiError.new("Response is not JSON: #{response.body}")
    end
  elsif response.status == 404
    raise NotFound.new("This resource was not found: #{path}")
  else
    if response.headers['content-type'] =~ /json/
      parsed = JSON.parse(response.body)
      # p parsed['ExceptionMessage']
      details = parsed['Message'] || parsed['ReturnMessage']
    else
      details = response.body
    end
    raise ApiError.new("#{response.status}: #{details}")
  end
end
get_all(params) click to toggle source

Returns a Hash; “Items” contains the array of items.

# File lib/thewalters/base.rb, line 24
def self.get_all(params)
  path = [version, api_path].join("/")
  result = fetch(path, params)
  result["Items"] = result["Items"].map {|o| self.new(o) }
  result
end
get_by_id(id) click to toggle source
# File lib/thewalters/base.rb, line 31
def self.get_by_id(id)
  path = [version, api_path, id].join("/")
  result = fetch(path)
  object = result["Data"]
  self.new(object)
end
get_images(id) click to toggle source
# File lib/thewalters/base.rb, line 45
def self.get_images(id)
  path = [version, api_path, id, 'images'].join("/")
  result = fetch(path)
  result["Items"] = result["Items"].map {|o| Image.new(o) }
  result
end
get_objects(id, params) click to toggle source
# File lib/thewalters/base.rb, line 38
def self.get_objects(id, params)
  path = [version, api_path, id, 'objects'].join("/")
  result = fetch(path, params)
  result["Items"] = result["Items"].map {|o| ArtObject.new(o) }
  result
end
path() click to toggle source
# File lib/thewalters/base.rb, line 54
def self.path
  raise "Path not defined for this class"
end
version() click to toggle source
# File lib/thewalters/base.rb, line 52
def self.version; "v1" end