Class: Her::Middleware::CacheUnmodified
- Inherits:
-
Faraday::Middleware
- Object
- Faraday::Middleware
- Her::Middleware::CacheUnmodified
- Defined in:
- lib/her_cache_unmodified.rb
Overview
Easy way to begin support 304 status, so on ther side if data was not changed You will load it from local cache. Of course, other side must support Of course, other side must support 304 status also. Here is Rails controller example with this support:
class Post < ApplicationController
before_action :check_changes
private
def check_changes
return unless request.headers['HTTP_IF_MODIFIED_SINCE']
return if request.headers['HTTP_IF_MODIFIED_SINCE'].to_datetime > resource.updated_at
render body: nil, status: 304
end
end
Constant Summary collapse
- SAVE_METHODS =
[:get, :head].freeze
Instance Attribute Summary collapse
-
#cache ⇒ Object
readonly
Returns the value of attribute cache.
-
#options ⇒ Object
readonly
Returns the value of attribute options.
-
#url ⇒ Object
Returns the value of attribute url.
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app, options = {}) ⇒ CacheUnmodified
constructor
apply with optinos: cache # default value is Rails.cache if Rails is used cache_key_prefix # defauilt is nil.
Constructor Details
#initialize(app, options = {}) ⇒ CacheUnmodified
apply with optinos: cache # default value is Rails.cache if Rails is used cache_key_prefix # defauilt is nil
27 28 29 30 31 32 |
# File 'lib/her_cache_unmodified.rb', line 27 def initialize(app, ={}) @app = app @cache = [:cache] @cache ||= Rails.cache if defined?(Rails) @options = end |
Instance Attribute Details
#cache ⇒ Object (readonly)
Returns the value of attribute cache.
20 21 22 |
# File 'lib/her_cache_unmodified.rb', line 20 def cache @cache end |
#options ⇒ Object (readonly)
Returns the value of attribute options.
20 21 22 |
# File 'lib/her_cache_unmodified.rb', line 20 def @options end |
#url ⇒ Object
Returns the value of attribute url.
21 22 23 |
# File 'lib/her_cache_unmodified.rb', line 21 def url @url end |
Instance Method Details
#call(env) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/her_cache_unmodified.rb', line 34 def call(env) return @app.call(env) unless SAVE_METHODS.include?(env[:method]) self.url = env.url.to_s env[:request_headers]["If-Modified-Since"] ||= cached_time if cached_time @app.call(env).on_complete do if env[:status] == 304 if cached_body env[:body] = cached_body # with out this hack Her crushes env[:status] = 200 end elsif env[:status] == 200 cache.write cache_key_body, env[:body], expires_in: cache_key_ttl cache.write cache_key_time, Time.zone.now.httpdate, expires_in: cache_key_ttl end end end |