Class: TimesPeople::Base

Inherits:
Object
  • Object
show all
Defined in:
lib/times_people/base.rb

Direct Known Subclasses

User

Constant Summary collapse

API_SERVER =
'api.nytimes.com'
API_VERSION =
'v1'
API_NAME =
'timespeople'
@@api_key =
nil
@@debug =
false

Class Method Summary collapse

Class Method Details

.api_keyObject

Returns the current value of the API Key



26
27
28
# File 'lib/times_people/base.rb', line 26

def self.api_key
	@@api_key
end

.api_key=(key) ⇒ Object

Set the API key used for operations. This needs to be called before any requests against the API. To obtain an API key, go to developer.nytimes.com/



16
17
18
# File 'lib/times_people/base.rb', line 16

def self.api_key=(key)
	@@api_key = key
end

.build_request_url(path, params) ⇒ Object

Builds a request URI to call the API server



32
33
34
35
36
# File 'lib/times_people/base.rb', line 32

def self.build_request_url(path, params)
	URI::HTTP.build :host => API_SERVER,
	:path => "/svc/#{API_NAME}/api/#{API_VERSION}/#{path}.js",
	:query => params.map {|k,v| "#{URI.escape(k)}=#{URI.escape(v)}"}.join('&')
end

.date_field(value) ⇒ Object



49
50
51
52
# File 'lib/times_people/base.rb', line 49

def self.date_field(value)
	return nil unless value =~ /^\d{8}$/
	Date.strptime(value, "%Y%m%d")
end

.debug=(flag) ⇒ Object



20
21
22
# File 'lib/times_people/base.rb', line 20

def self.debug=(flag)
	@@debug = flag
end

.integer_field(value) ⇒ Object



44
45
46
47
# File 'lib/times_people/base.rb', line 44

def self.integer_field(value)
	return nil if value.nil?
	value.to_i
end

.invoke(path, params = {}) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/times_people/base.rb', line 54

def self.invoke(path, params={})
	begin
		if @@api_key.nil?
			raise AuthenticationError, "You must initialize the API key before you run any API queries"
		end

		full_params = params.merge 'api-key' => @@api_key
		uri = build_request_url(path, full_params)	

		puts "REQUEST: #{uri}" if @@debug

		reply = uri.read
		parsed_reply = JSON.parse reply

		if parsed_reply.nil?
			raise BadResponseError, "Empty reply returned from API"
		end

		#case parsed_reply['status']
		# FIXME
		#end

		parsed_reply
	rescue OpenURI::HTTPError => e
		# FIXME: Return message from body?
		case e.message
		when /^400/
			raise BadRequestError
		when /^403/
			raise AuthenticationError
		when /^404/
			return nil
		when /^500/
			raise ServerError
		else
			raise ConnectionError
		end

		raise "Error connecting to URL #{uri} #{e}"
	rescue JSON::ParserError => e
		raise BadResponseError, "Invalid JSON returned from API:\n#{reply}"
	end
end

.text_field(value) ⇒ Object



38
39
40
41
42
# File 'lib/times_people/base.rb', line 38

def self.text_field(value)
	return nil if value.nil?
	coder = HTMLEntities.new
	coder.decode(value)
end