Module: Rotten::Api::ClassMethods
- Defined in:
- lib/rotten/api.rb
Instance Method Summary collapse
- #cache ⇒ Object
-
#cache=(_cache) ⇒ Object
Use your own cache, such as ActiveSupport::Cache::MemoryStore.
- #disable_cache! ⇒ Object
- #enable_cache! ⇒ Object
- #endpoint ⇒ Object
- #get(path, options = {}) ⇒ Object
- #get_from_cache(url) ⇒ Object
- #url_for(path, options = {}) ⇒ Object
- #use_cache? ⇒ Boolean
- #version ⇒ Object
- #write_to_cache(url, data) ⇒ Object
Instance Method Details
#cache ⇒ Object
38 39 40 41 |
# File 'lib/rotten/api.rb', line 38 def cache @cache ||= Cache.new @cache.store end |
#cache=(_cache) ⇒ Object
Use your own cache, such as ActiveSupport::Cache::MemoryStore
44 45 46 47 |
# File 'lib/rotten/api.rb', line 44 def cache=(_cache) enable_cache! @cache = Cache.new :store => _cache end |
#disable_cache! ⇒ Object
34 35 36 |
# File 'lib/rotten/api.rb', line 34 def disable_cache! @use_cache = false end |
#enable_cache! ⇒ Object
30 31 32 |
# File 'lib/rotten/api.rb', line 30 def enable_cache! @use_cache = true end |
#endpoint ⇒ Object
18 19 20 |
# File 'lib/rotten/api.rb', line 18 def endpoint "http://api.rottentomatoes.com/api/public/v#{version}" end |
#get(path, options = {}) ⇒ Object
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/rotten/api.rb', line 59 def get path, ={} if Rotten.api_key.nil? raise UndefinedApiKeyError, "Please define your API key with Rotten.api_key=(your_key)" end url = url_for(path, ) cached = get_from_cache(url) if cached puts "Using cache.." 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
49 50 51 52 53 |
# File 'lib/rotten/api.rb', line 49 def get_from_cache url if use_cache? cache.read(url) end end |
#url_for(path, options = {}) ⇒ Object
86 87 88 89 90 91 92 93 94 95 96 |
# File 'lib/rotten/api.rb', line 86 def url_for(path, ={}) path.gsub! /\.json\Z/, '' params = '' if .keys.any? .each_pair{|k,v| params << "#{k}=#{URI.escape(v)}&" } end params.chomp! "&" if params "#{endpoint}/#{path}.json?apikey=#{Rotten.api_key}&#{params}" end |
#use_cache? ⇒ Boolean
26 27 28 |
# File 'lib/rotten/api.rb', line 26 def use_cache? @use_cache == true end |
#version ⇒ Object
22 23 24 |
# File 'lib/rotten/api.rb', line 22 def version '1.0' end |
#write_to_cache(url, data) ⇒ Object
55 56 57 |
# File 'lib/rotten/api.rb', line 55 def write_to_cache url, data cache.write(url, data) if use_cache? end |