Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion lib/lotus/action/cookie_jar.rb
Original file line number Diff line number Diff line change
Expand Up @@ -98,13 +98,23 @@ def []=(key, value)
# @api private
def _merge_default_values(value)
cookies_options = if value.is_a? Hash
value
value.merge(_add_expires_option(value) || {})
else
{ value: value }
end
@default_options.merge cookies_options
end

# Add expires option to cookies if :max_age presents
#
# @since x.x.x
# @api private
def _add_expires_option(value)
if value.has_key?(:max_age) && !value.has_key?(:expires)
{ expires: (Time.now + value[:max_age]) }
end
end

# Extract the cookies from the raw Rack env.
#
# This implementation is borrowed from Rack::Request#cookies.
Expand Down
12 changes: 12 additions & 0 deletions test/cookies_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -62,5 +62,17 @@ def include?(hash)
headers.must_equal({'Content-Type' => 'application/octet-stream; charset=utf-8', 'Set-Cookie' => 'bar=foo; domain=lotusrb.com; path=/action'})
end
end

describe 'with max_age option and without expires option' do
it 'automatically set expires option' do
Time.stub :now, Time.now do
action = GetAutomaticallyExpiresCookiesAction.new
_, headers, _ = action.call({})
max_age = 120
headers["Set-Cookie"].must_include("max-age=#{max_age}")
headers["Set-Cookie"].must_include("expires=#{(Time.now + max_age).gmtime.rfc2822}")
end
end
end
end
end
9 changes: 9 additions & 0 deletions test/fixtures.rb
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,15 @@ def call(params)
end
end

class GetAutomaticallyExpiresCookiesAction
include Lotus::Action
include Lotus::Action::Cookies

def call(params)
cookies[:bar] = { value: 'foo', max_age: 120 }
end
end

class SetCookiesAction
include Lotus::Action
include Lotus::Action::Cookies
Expand Down