diff --git a/lib/lotus/action/cookie_jar.rb b/lib/lotus/action/cookie_jar.rb index 279d90fd..6a4dd443 100644 --- a/lib/lotus/action/cookie_jar.rb +++ b/lib/lotus/action/cookie_jar.rb @@ -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. diff --git a/test/cookies_test.rb b/test/cookies_test.rb index 7fd514ac..a6b19acd 100644 --- a/test/cookies_test.rb +++ b/test/cookies_test.rb @@ -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 diff --git a/test/fixtures.rb b/test/fixtures.rb index f03ba630..398cc5cb 100644 --- a/test/fixtures.rb +++ b/test/fixtures.rb @@ -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