Enable Sessions

Sessions are available in Hanami applications, but not enabled by default. If we want to turn on this feature, we just need to uncomment a line of code.

  1. # apps/web/application.rb
  2. module Web
  3. class Application < Hanami::Application
  4. configure do
  5. # ...
  6. sessions :cookie, secret: ENV['WEB_SESSIONS_SECRET']
  7. end
  8. end
  9. end

The first argument is the name of the adapter for the session storage. The default value is :cookie, that uses Rack::Session::Cookie.

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

We can use a different storage compatible with Rack sessions. Let’s say we want to use Redis. We should bundle redis-rack and specify the name of the adapter: :redis. Hanami is able to autoload the adapter and use it when the application is started.

Custom storage technologies are autoloaded via require "rack/session/#{ adapter_name }".

The second argument passed to sessions is a Hash of options that are passed to the adapter. We find only a default :secret, but we can specify all the values that are supported by the current adapter.

Usage

Sessions 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. session[:b] # read
  9. session[:a] = 'foo' # assign
  10. session[:c] = nil # remove
  11. end
  12. end
  13. end
  14. end
  15. end

Sharing session values between applications

To share session values, defined in one application, we must provide the same session secret to all the applications where we need those values.

  1. # Define ENV variables for development environment
  2. WEB_SESSIONS_SECRET="123456789"
  3. ADMIN_SESSIONS_SECRET="123456789"

Set session variable in the first app.

  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. session[:a] = 'foo' # assign
  9. end
  10. end
  11. end
  12. end
  13. end

Read session variable in the second app.

  1. # apps/admin/controllers/dashboard/index.rb
  2. module Admin
  3. module Controllers
  4. module Dashboard
  5. class Index
  6. include Admin::Action
  7. def call(params)
  8. session[:a] # read => 'foo'
  9. end
  10. end
  11. end
  12. end
  13. end