Skip to content

Instantly share code, notes, and snippets.

@johnbintz
Created January 14, 2014 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnbintz/8410794 to your computer and use it in GitHub Desktop.
Save johnbintz/8410794 to your computer and use it in GitHub Desktop.
Ruby example for using The Game Crafter API.
source 'https://rubygems.org'
gem 'httmultiparty'
#!/usr/bin/env ruby
# This Ruby client for The Game Crafter is more involved than simply using HTTParty standalone.
# With this code, you can expand upon the client and easily add your own encapsulated functionality!
# It also shows some good Ruby design practices if you're still new to the language.
# You'll need at least Ruby 1.9.3 or so and Bundler.
# make it easy to do multi-part requests
require 'httmultiparty'
module TheGameCrafter
# wrap up our basic client actions in a class
class Client
include HTTMultiParty
base_uri 'https://www.thegamecrafter.com/api'.freeze
# we set these in the initializer...
attr_accessor :api_key, :username, :password
# these get set after #get_session!
attr_reader :user_id, :session_id
def initialize(username, password, api_key)
@username, @password, @api_key = username, password, api_key
end
# get a session and user id
def get_session!
response = post '/session', query: { 'username' => username, 'password' => password, 'api_key_id' => api_key }
@session_id = response['id']
@user_id = response['user_id']
end
# get user account info
def account_info
get '/user/' + @user_id, query: default_query_params
end
# upload a file
# provide an IO that responds to #path. A File is good!
def upload_file(io, folder_id)
post '/file', query: { 'name' => File.basename(io.path), 'folder_id' => folder_id, 'file' => io }.merge(default_query_params)
end
# search for games
def search_games(query)
get '/game', query: { 'q' => query }.merge(default_query_params)
end
private
# wrappers around HTTParty to handle TGC responses automagically
def post(*args)
response = self.class.post *args
response.parsed_response['result']
end
def get(*args)
response = self.class.get *args
response.parsed_response['result']
end
# we use this a lot. factor it out.
def default_query_params
{ 'session_id' => session_id }
end
end
end
client = TheGameCrafter::Client.new('username', 'password', 'api key')
client.get_session!
account_info = client.account_info
p client.upload_file File.open('file.jpg'), account_info['root_folder_id']
p client.search_games "Steampunk"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment