水口玄造 水口玄造 - 3 months ago 18
Ruby Question

Set cookie expiration time in Ruby

I am using Ruby with Sinatra do develop a web application.
I have Ruby version 2.3.0, Sinatra 5.0.30

Following the suggestions from Rails cookies, set start date and expire date, I tried this:

@language = 'en-US'
response.set_cookie(:USER_LANGUAGE, :value => @language, :expires => 1.hour.from_now, :domain => '.example.com')


At first I thought it worked because the cookie set except the expiration time is still just only for the session. The error in my Apache error log says this:
NoMethodError - undefined method 'hour' for 1:Fixnum:


Please note: none of these worked to resolve the problem (none of them could be properly found by the compiler)


  1. require 'active_support'

  2. require 'active_support/all'

  3. require 'activesupport'



So, I tried this instead:

@language = 'en-US'
response.set_cookie(:USER_LANGUAGE, :value => @language, :expires => 30, :domain => '.example.com')


Just to see what would happen and nothing changed, it still only expires with the session.

How should I go about setting an expiration time for my cookies in Ruby with Sinatra?

Answer

Sinatra doesn't have the ActiveSupport library which provides a helper for number-to-time, so 1.hour.from_now doesn't works here.

You should use this:

class SinatraApp < Sinatra::Base

use Rack::Session::Cookie, :key => 'rack.session',
                           :domain => 'foo.com',
                           :path => '/',
                           :expire_after => 2592000, # In seconds
                           :secret => 'some_secret'

And set a time in seconds. Because the Sinatra session comes from Rack::Session.

HOW TO ENABLE SESSIONS WITH SINATRA

Comments