Module: NytimesArticle
- Defined in:
- lib/nytimes-article.rb,
lib/nytimes-article/version.rb
Constant Summary collapse
- API_SERVER =
'api.nytimes.com'
- API_VERSION =
'v1'
- API_NAME =
'search'
- API_BASE =
"/svc/#{API_NAME}/#{API_VERSION}/article"
- VERSION =
"0.0.3"
- @@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(params) ⇒ Object
Builds a request URI to call the API server.
- .datetime_parser(datetime) ⇒ Object
- .search(params = {}) ⇒ Object
- .semantic_api_key=(key) ⇒ Object
Class Method Details
.api_key ⇒ Object
25 26 27 |
# File 'lib/nytimes-article.rb', line 25 def 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/
21 22 23 |
# File 'lib/nytimes-article.rb', line 21 def api_key=(key) @@api_key = key end |
.build_request_url(params) ⇒ Object
Builds a request URI to call the API server
43 44 45 |
# File 'lib/nytimes-article.rb', line 43 def build_request_url(params) URI::HTTP.build :host => API_SERVER, :path => API_BASE, :query => params.map {|k,v| "#{k}=#{v}"}.join('&') end |
.datetime_parser(datetime) ⇒ Object
37 38 39 |
# File 'lib/nytimes-article.rb', line 37 def datetime_parser(datetime) datetime ? DateTime.parse(datetime) : nil end |
.search(params = {}) ⇒ Object
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/nytimes-article.rb', line 47 def search(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, 'format' => 'json' uri = build_request_url(full_params) reply = uri.read parsed_reply = JSON.parse reply if parsed_reply.nil? raise "Empty reply returned from API" end 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
29 30 31 |
# File 'lib/nytimes-article.rb', line 29 def semantic_api_key=(key) @@semantic_api_key = key end |