Module: Rotten::Api::ClassMethods

Defined in:
lib/rotten/api.rb

Instance Method Summary collapse

Instance Method Details

#cacheObject



46
47
48
49
# File 'lib/rotten/api.rb', line 46

def cache
  @cache ||= Cache.new
  @cache.store
end

#cache=(_cache) ⇒ Object

Use your own cache, such as ActiveSupport::Cache::MemoryStore



52
53
54
55
# File 'lib/rotten/api.rb', line 52

def cache=(_cache)
  enable_cache!
  @cache = Cache.new :store => _cache
end

#disable_cache!Object



42
43
44
# File 'lib/rotten/api.rb', line 42

def disable_cache!
  @use_cache = false
end

#enable_cache!Object



38
39
40
# File 'lib/rotten/api.rb', line 38

def enable_cache!
  @use_cache = true
end

#endpointObject



22
23
24
# File 'lib/rotten/api.rb', line 22

def endpoint
  "http://api.rottentomatoes.com/api/public/v#{version}"
end

#extract_info(klass, json = {}) ⇒ Object



105
106
107
108
109
110
111
# File 'lib/rotten/api.rb', line 105

def extract_info klass, json={}
  if json.is_a?(Array)
    json.map{|m| extract_info(klass, m) }
  else
    klass.new(json)
  end
end

#get(path, options = {}) ⇒ Object



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
# File 'lib/rotten/api.rb', line 67

def get path, options={}
  if Rotten.api_key.nil?
    raise UndefinedApiKeyError, "Please define your API key with Rotten.api_key=(your_key)"
  end

  url    = url_for(path, options)
  cached = get_from_cache(url)
  if cached
    if block_given?
      return yield(cached)
    else
      return cached
    end
  end

  open( url ) do |response|
    data = JSON.parse(response.read)
    write_to_cache url, data
    if block_given?
      yield(data)
    else
      data
    end
  end
end

#get_from_cache(url) ⇒ Object



57
58
59
60
61
# File 'lib/rotten/api.rb', line 57

def get_from_cache url
  if use_cache?
    cache.read(url)
  end
end

#maximum_per_pageObject



30
31
32
# File 'lib/rotten/api.rb', line 30

def maximum_per_page
  '50'
end

#url_for(path, options = {}) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
# File 'lib/rotten/api.rb', line 93

def url_for(path, options={})
  path.gsub! /\.json\Z/, ''
  
  params = ''
  if options.keys.any?
    options.each_pair{|k,v| params << "#{k}=#{URI.escape(v.to_s)}&" }
  end
  params.chomp! "&" if params

  "#{endpoint}/#{path}.json?apikey=#{Rotten.api_key}&#{params}"
end

#use_cache?Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/rotten/api.rb', line 34

def use_cache?
  @use_cache == true
end

#versionObject



26
27
28
# File 'lib/rotten/api.rb', line 26

def version
  '1.0'
end

#write_to_cache(url, data) ⇒ Object



63
64
65
# File 'lib/rotten/api.rb', line 63

def write_to_cache url, data
  cache.write(url, data) if use_cache?
end