Class: TimesWire::Base

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

Direct Known Subclasses

Item, Section

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
nil
@@semantic_api_key =
nil

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.api_keyObject



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.message =~ /^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

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