user1095945
user1095945

Reputation: 11

How to access Sinatra Session from a module

I am developing an application with Ruby 1.9.2 and Sinatra 1.3. I have a helper module that needs to access session data. Here is a snippet of my module

require 'sinatra'

module SessionHelper

  def current_user
    session['current_user']
  end

end

This works fine with ruby 1.8.7, but when I run the application with Ruby 1.9.2, I get an error saying: undefined local variable or method 'session' for SessionHelper:Module

Upvotes: 1

Views: 1380

Answers (1)

ghstcode
ghstcode

Reputation: 2912

try something like this:

require 'sinatra/base'

module Sinatra
  module SessionHelper
    def current_user
      session['current_user']
    end
  end
  register current_user
end

Then in your controllers somewhere, you could do this:

user = current_user

Take a look at the documentation on writing Sinatra extensions - it applies to other custom modules too.

Hope that helps!

Upvotes: 2

Related Questions