Class: TomatoPower::APIService

Inherits:
Object
  • Object
show all
Defined in:
lib/tomato_power/api/api_service.rb

Overview

API service to interface with Rotten Tomatoes API

Constant Summary collapse

MAX_PAGE_LIMIT =
50
API_VERSION =
'v1.0'
BASE_URL =
"http://api.rottentomatoes.com/api/public/#{API_VERSION}"
MOVIE_URL =
"#{ BASE_URL }/movies/"
LIST_URL =
"#{ BASE_URL }/lists/"

Class Method Summary collapse

Class Method Details

.api_url(endpoint, api_key, options = {}) ⇒ Object

Note:

see TOMATO_METHODS or / Rotten Tomatoes API for valid options.

Constructs the API URL path depending on the options being passed in. Since the options are being checked against a whitelist before reaching this point, it is guaranteed that the options here are valid.

The URL is constructed by introspecting the options. Only search calls contain the :q symbol, therefore a search_url is created. Likewise for movie specific searches requiring a :movie_id.

Parameters:

  • endpoint (String)

    the end point of the API call.

  • options (Hash<String>) (defaults to: {})

    options for the API call.



37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/tomato_power/api/api_service.rb', line 37

def self.api_url endpoint, api_key, options={}
  if movie_id = options[:movie_id]
    options.delete :movie_id
    endpoint = endpoint.dup.insert(0, movie_id.to_s)
    url = MOVIE_URL
  elsif options[:q] || options[:id]
    url = BASE_URL
  else
    url = LIST_URL
  end
  "#{url}#{endpoint}apikey=#{api_key}#{request_params(options)}"
end

.fetch(endpoint, api_key, options = {}) ⇒ Object

Gets the url then parses results.

Parameters:

  • endpoint (String)

    API url.

  • api_key (String)

    Client API key

  • options (Hash) (defaults to: {})

    options for the API call



20
21
22
23
# File 'lib/tomato_power/api/api_service.rb', line 20

def self.fetch endpoint, api_key, options={}
  tomato = get api_url(endpoint, api_key, options)
  parse(tomato) if tomato
end

.options_valid?(method, options = {}) ⇒ true, false

Note:

An option is valid when it is present in the :whitelist of the corresponding method in TOMATO_METHODS.

Checks whether or not the received options are valid for a given method.

Parameters:

  • method (Symbol)

    method being called.

  • options (Hash) (defaults to: {})

    options for the method.

Returns:

  • (true, false)


56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/tomato_power/api/api_service.rb', line 56

def self.options_valid? method, options={}
  options.each_key do |option|
    if option == :page_limit && options[:page_limit] > MAX_PAGE_LIMIT
      options[:pagelimit] = MAX_PAGE_LIMIT 
    end
    unless TOMATO_METHODS[method][:whitelist].include?(option)
      raise ArgumentError.new(
        "Invalid key: #{option} for #{method}.
    Valid keys are #{TOMATO_METHODS[method][:whitelist]}."
      )
      false
    end
  end
  true
end