Sessions are disabled by default. To enable sessions, add a config like the following to your app:

  1. # config/app.rb
  2. module Bookshelf
  3. class App < Hanami::App
  4. config.actions.sessions = :cookie, {
  5. key: "bookshelf.session",
  6. secret: settings.session_secret,
  7. expire_after: 60*60*24*365
  8. }
  9. end
  10. end

For this to work, you will need to add a session_secret to your app settings. See settings for more details.

  1. # config/settings.rb
  2. module Bookshelf
  3. class Settings < Hanami::Settings
  4. setting :session_secret, constructor: Types::String
  5. end
  6. end

Using sessions

With sessions enabled, actions can set and read values from the session using the response and request objects.

  1. module Bookshelf
  2. module Actions
  3. module Books
  4. class Index < Bookshelf::Action
  5. def handle(request, response)
  6. # Setting a value in the session
  7. response.session[:user_id] = 1
  8. # Reading a value from the session
  9. request.session[:user_id] # => 1
  10. # Removing a value from the session
  11. request.session[:user_id] = nil
  12. end
  13. end
  14. end
  15. end
  16. end

Session adapters

When configuring sessions, the first argument of the configuration is the adapter to use for session storage.

Specifying :cookie, as above, will use Rack::Session::Cookie for the session storage.

The name of the session adapter is the underscored version of the class name under Rack::Session namespace. Example: :cookie for Rack::Session::Cookie.

To use a different adapter, for example :redis, add the redis-rack gem and specify the adapter as :redis.

Custom storage technologies can be loaded via require "rack/session/#{ adapter_name }".

The second argument passed to sessions is a hash of options to be passed to the chosen adapter.