Class: Rack::Cachely::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/rack-cachely/context.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Context

Returns a new instance of Context.



5
6
7
# File 'lib/rack-cachely/context.rb', line 5

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/rack-cachely/context.rb', line 13

def call(env)
  @env = env
  if self.perform_caching?
    handle_refresh_request
    results = Rack::Cachely::Store.get(key)
    if results
      return results
    end
  end
  results = @app.call(@env)
  if self.perform_caching? && is_cacheable?(results)
    Rack::Cachely::Store.post(key, results, age: @age.to_i)
  end
  return results
end

#configObject



60
61
62
# File 'lib/rack-cachely/context.rb', line 60

def config
  Rack::Cachely.config
end

#handle_refresh_requestObject



29
30
31
32
33
# File 'lib/rack-cachely/context.rb', line 29

def handle_refresh_request
  if request.params["refresh-cachely"]
    Rack::Cachely::Store.delete(key)
  end
end

#is_cacheable?(results) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
47
48
49
50
51
52
53
54
# File 'lib/rack-cachely/context.rb', line 44

def is_cacheable?(results)
  status = results[0].to_i
  return false unless (200...300).include?(status)
  headers = results[1]
  control = headers["Cache-Control"]
  if /public/.match(control) && /max-age=(\d+)/.match(control)# && !/\/assets\//.match(key.to_s)
    @age = $1
    return true
  end
  return false
end

#keyObject



56
57
58
# File 'lib/rack-cachely/context.rb', line 56

def key
  @key ||= Rack::Cachely::Key.new(request)
end

#perform_caching?Boolean

Returns:

  • (Boolean)


35
36
37
38
39
40
41
42
# File 'lib/rack-cachely/context.rb', line 35

def perform_caching?
  perform_caching = if defined?(Rails)
    Rails.application.config.action_controller.perform_caching
  else
    @env['rack-cachely.perform_caching'].to_s == 'true'
  end
  perform_caching && config.enabled && request.request_method == 'GET' && !request.params["no-cachely"]
end

#requestObject



9
10
11
# File 'lib/rack-cachely/context.rb', line 9

def request
  @request ||= Rack::Request.new(@env.dup)
end