Actions can set cookies on outgoing requests via the response object.

  1. module Bookshelf
  2. module Actions
  3. module Books
  4. class Index < Bookshelf::Action
  5. def handle(request, response)
  6. response.cookies["tasty_cookie"] = "strawberry"
  7. end
  8. end
  9. end
  10. end
  11. end

Cookies subsequently sent by the browser can be read from the request.

  1. module Bookshelf
  2. module Actions
  3. module Books
  4. class Index < Bookshelf::Action
  5. def handle(request, response)
  6. request.cookies["tasty_cookie"] # => "strawberry"
  7. end
  8. end
  9. end
  10. end
  11. end

You can set one or more of the following options for cookies issued by actions using the action cookies config on your app.

  • :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
  1. # config/app.rb
  2. module Bookshelf
  3. class App < Hanami::App
  4. config.actions.cookies = {
  5. domain: "hanami.example.com",
  6. secure: true,
  7. httponly: true,
  8. path: "/foo",
  9. max_age: 300
  10. }
  11. end
  12. end

This configuration can be overridden within an action passing a hash, which has a value key representing the value of the cookie, and any properties to override.

  1. module Bookshelf
  2. module Actions
  3. module Books
  4. class Index < Bookshelf::Action
  5. def handle(request, response)
  6. response.cookies["tasty_cookie"] = "strawberry"
  7. response.cookies["longer_lived_cookie"] = {
  8. value: "anzac_biscuit",
  9. max_age: 604800
  10. }
  11. end
  12. end
  13. end
  14. end
  15. end

Removing cookies

To remove a cookie, assign it the value nil.

  1. response.cookies["tasty_cookie"] = nil

Disabling cookies

To prevent cookies from being set in your actions, provide the following config to your app:

  1. # config/app.rb
  2. module Bookshelf
  3. class App < Hanami::App
  4. config.actions.cookies = nil
  5. end
  6. end