Skip to content

Commit

Permalink
Convenient cache and content type for response generation
Browse files Browse the repository at this point in the history
These three convenient methods make it easy to declaratively specify how a response should be structured. For example:

    response.do_not_cache!

    response.cache!

    response.content_type! 'text/html'

Open to discussion w.r.t. naming, and behaviour. I monkey patch these in which might be fine for my usage, but I thought it could be useful to a wider audience.
  • Loading branch information
ioquatix committed Sep 8, 2015
1 parent a46eae2 commit ed33cd7
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/rack.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ def self.release
SERVER_ADDR = 'SERVER_ADDR'.freeze
SERVER_PORT = 'SERVER_PORT'.freeze
CACHE_CONTROL = 'Cache-Control'.freeze
EXPIRES = 'Expires'.freeze
CONTENT_LENGTH = 'Content-Length'.freeze
CONTENT_TYPE = 'Content-Type'.freeze
SET_COOKIE = 'Set-Cookie'.freeze
Expand Down
19 changes: 19 additions & 0 deletions lib/rack/response.rb
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,25 @@ def set_cookie(key, value)
def delete_cookie(key, value={})
set_header SET_COOKIE, ::Rack::Utils.add_remove_cookie_to_header(get_header(SET_COOKIE), key, value)
end

# Specifies that the content shouldn't be cached. Overrides `cache!` if already called.
def do_not_cache!
set_header CACHE_CONTROL, "no-cache, must-revalidate"
set_header EXPIRES, Time.now.httpdate
end

# Specify that the content should be cached.
def cache!(duration = 3600)
unless headers[CACHE_CONTROL] =~ /no-cache/
set_header CACHE_CONTROL, "public, max-age=#{duration}"
set_header EXPIRES, (Time.now + duration).httpdate
end
end

# Specify the content type of the response data.
def content_type!(value)
set_header CONTENT_TYPE, value.to_s
end
end

include Helpers
Expand Down

0 comments on commit ed33cd7

Please sign in to comment.