Enable Cookies

Hanami applies “batteries included, but not installed” philosophy. Cookies are a feature that is present but needs to be activated.

In our application settings there is a line to uncomment.

  1. # apps/web/application.rb
  2. module Web
  3. class Application < Hanami::Application
  4. configure do
  5. # ...
  6. cookies true
  7. end
  8. end
  9. end

From now on, cookies are automatically sent for each response.

Settings

With that configuration we can specify options that will be set for all cookies we send from our application.

  • :domain - String (nil by default), the domain
  • :path - String (nil by default), a relative URL
  • :max_age - Integer (nil by default), cookie duration expressed in seconds
  • :secure - Boolean (true by default if using SSL), restrict cookies to secure connections
  • :httponly - Boolean (true by default), restrict JavaScript access to cookies

Usage

Cookies behave like a Hash: we can read, assign and remove values.

  1. # apps/web/controllers/dashboard/index.rb
  2. module Web
  3. module Controllers
  4. module Dashboard
  5. class Index
  6. include Web::Action
  7. def call(params)
  8. cookies[:b] # read
  9. cookies[:a] = 'foo' # assign
  10. cookies[:c] = nil # remove
  11. cookies[:d] = { value: 'foo', path: '/bar' } # assign with options
  12. end
  13. end
  14. end
  15. end
  16. end

When setting a value, a cookie can accept a String or a Hash to specify inline options. General settings are applied automatically but these options can be used to override values case by case.

Example

  1. # apps/web/application.rb
  2. module Web
  3. class Application < Hanami::Application
  4. configure do
  5. # ...
  6. cookies max_age: 300 # 5 minutes
  7. end
  8. end
  9. end

We’re going to set two cookies from the action: the first will inherit application configuration, while the second overrides the default value.

  1. # apps/web/controllers/dashboard/index.rb
  2. module Web
  3. module Controllers
  4. module Dashboard
  5. class Index
  6. include Web::Action
  7. def call(params)
  8. # Set-Cookie:a=foo; max-age=300; HttpOnly
  9. cookies[:a] = 'foo'
  10. # Set-Cookie:b=bar; max-age=100; HttpOnly
  11. cookies[:b] = { value: 'bar', max_age: 100 }
  12. end
  13. end
  14. end
  15. end
  16. end