Sha256: 2d54609094ba88ec56ce0d053393f36fbde1e45ea702b364f318e09456b23b93

Contents?: true

Size: 1.37 KB

Versions: 1

Compression:

Stored size: 1.37 KB

Contents

module Zunnit		
  
  # Singleton API Accessor
  def self.api
    @api ||= Api.new
  end
  
  # API Class
	class Api
		attr_accessor :client, :key, :version
		
		def initialize
			self.client		= Zunnit.client
			self.key			= Zunnit.key
			self.version	= Zunnit.version		
			
			yield self if block_given?
		end
				
		# Make a GET request to Zunnit's API
		def get(action, options={})
			request(:get, action, options)
		end
		
		# Make a POST request to Zunnit's API
		def post(action, options={})
			request(:post, action, options)
		end	
		
		private
			def connection
				@connection ||= Faraday.new(:url => Zunnit::URL)
			end

			def params_for(options={})
				return {
					:api_key	=> self.key
				}.merge(options)
			end

			# Make a request to Zunnit's API
			def request(http_method, action, options={})
				# Raise error if the actions is invalid
				unless Zunnit.actions[action]
					raise "Invalid action \"#{action}\"" 
				end

				# Raise error if the http method is invalid
				unless [:get, :post].include? http_method
					raise "Invalid http_method \"#{http_method}\"" 
				end

				# Make the Request
				action_url	= "/#{client}#{Zunnit.actions[action]}"
				response = connection.send(http_method) do |req|
					req.url(action_url)
					req.params	= params_for options 
				end

				# return HASH for body JSON 
				JSON response.body, :symbolize_names => true
			end
	end 
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
zunnit-0.2.0 lib/zunnit/api.rb