Class: TimesWire::Base
- Inherits:
-
Object
- Object
- TimesWire::Base
- Defined in:
- lib/times_wire/base.rb
Constant Summary collapse
- API_SERVER =
'api.nytimes.com'
- API_VERSION =
'v3'
- API_NAME =
'news'
- API_BASE =
"/svc/#{API_NAME}/#{API_VERSION}/content"
- @@api_key =
nil
- @@debug =
false
- @@copyright =
nil
- @@semantic_api_key =
nil
Class Method Summary collapse
- .api_key ⇒ Object
-
.api_key=(key) ⇒ Object
Set the API key used for operations.
-
.build_request_url(path, params) ⇒ Object
Builds a request URI to call the API server.
- .datetime_parser(datetime) ⇒ Object
- .invoke(path, params = {}) ⇒ Object
- .semantic_api_key=(key) ⇒ Object
Instance Method Summary collapse
-
#copyright ⇒ Object
The copyright footer to be placed at the bottom of any data from the New York Times.
Class Method Details
.api_key ⇒ Object
29 30 31 |
# File 'lib/times_wire/base.rb', line 29 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/
25 26 27 |
# File 'lib/times_wire/base.rb', line 25 def self.api_key=(key) @@api_key = key end |
.build_request_url(path, params) ⇒ Object
Builds a request URI to call the API server
47 48 49 |
# File 'lib/times_wire/base.rb', line 47 def self.build_request_url(path, params) URI::HTTP.build :host => API_SERVER, :path => "#{API_BASE}/#{path}.json", :query => params.map {|k,v| "#{k}=#{v}"}.join('&') end |
.datetime_parser(datetime) ⇒ Object
41 42 43 |
# File 'lib/times_wire/base.rb', line 41 def self.datetime_parser(datetime) datetime ? DateTime.parse(datetime) : nil end |
.invoke(path, params = {}) ⇒ Object
51 52 53 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 |
# File 'lib/times_wire/base.rb', line 51 def self.invoke(path, params={}) begin if @@api_key.nil? raise "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) reply = uri.read parsed_reply = JSON.parse reply if parsed_reply.nil? raise "Empty reply returned from API" end @@copyright = parsed_reply['copyright'] parsed_reply rescue OpenURI::HTTPError => e if e. =~ /^404/ return nil end raise "Error connecting to URL #{uri} #{e}" end end |
.semantic_api_key=(key) ⇒ Object
33 34 35 |
# File 'lib/times_wire/base.rb', line 33 def self.semantic_api_key=(key) @@semantic_api_key = key end |
Instance Method Details
#copyright ⇒ Object
The copyright footer to be placed at the bottom of any data from the New York Times. Note this is only set after an API call.
19 20 21 |
# File 'lib/times_wire/base.rb', line 19 def copyright @@copyright end |