Class: ContentGateway::Cache
- Inherits:
-
Object
- Object
- ContentGateway::Cache
- Defined in:
- lib/content_gateway/cache.rb
Instance Attribute Summary collapse
-
#status ⇒ Object
readonly
Returns the value of attribute status.
Instance Method Summary collapse
- #fetch(request, params = {}) ⇒ Object
-
#initialize(config, url, method, params = {}) ⇒ Cache
constructor
A new instance of Cache.
- #serve_stale ⇒ Object
- #stale_key ⇒ Object
- #use? ⇒ Boolean
Constructor Details
#initialize(config, url, method, params = {}) ⇒ Cache
Returns a new instance of Cache.
5 6 7 8 9 10 |
# File 'lib/content_gateway/cache.rb', line 5 def initialize(config, url, method, params = {}) @config = config @url = url @method = method.to_sym @skip_cache = params[:skip_cache] || false end |
Instance Attribute Details
#status ⇒ Object (readonly)
Returns the value of attribute status.
3 4 5 |
# File 'lib/content_gateway/cache.rb', line 3 def status @status end |
Instance Method Details
#fetch(request, params = {}) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/content_gateway/cache.rb', line 16 def fetch(request, params = {}) timeout = params[:timeout] || @config.timeout expires_in = params[:expires_in] || @config.cache_expires_in stale_expires_in = params[:stale_expires_in] || @config.cache_stale_expires_in begin Timeout.timeout(timeout) do @config.cache.fetch(@url, expires_in: expires_in) do @status = "MISS" response = request.execute response = String.new(response) if response @config.cache.write(stale_key, response, expires_in: stale_expires_in) response end end rescue Timeout::Error => e begin serve_stale rescue ContentGateway::StaleCacheNotAvailableError raise ContentGateway::TimeoutError.new(@url, e, timeout) end rescue ContentGateway::ServerError => e begin serve_stale rescue ContentGateway::StaleCacheNotAvailableError raise e end end end |
#serve_stale ⇒ Object
49 50 51 52 53 54 |
# File 'lib/content_gateway/cache.rb', line 49 def serve_stale @config.cache.read(stale_key).tap do |cached| raise ContentGateway::StaleCacheNotAvailableError.new unless cached @status = "STALE" end end |
#stale_key ⇒ Object
56 57 58 |
# File 'lib/content_gateway/cache.rb', line 56 def stale_key @stale_key ||= "stale:#{@url}" end |
#use? ⇒ Boolean
12 13 14 |
# File 'lib/content_gateway/cache.rb', line 12 def use? !@skip_cache && [:get, :head].include?(@method) end |