How do I access the session in a rails plugin?

I’m trying to access the session in a rails plugin, so as to set it as

  1. module Juggernaut
  2. def self.set_channels(chan)
  3. session[:juggernaut_channels] = chan
  4. end
  5. end
  6. module ActionController
  7. class Base
  8. include Juggernaut
  9. end
  10. end

At the moment I get: undefined local variable or method `session’ for

Here’s an example of session access within a module included in a
controller (which could be witihin a plugin or not).

module LogSession
def log_session

class ApplicationController < ActionController::Base
include LogSession
before_filter :log_session


With the code you’ve got here, set_channels is a method of the module
Juggernaut (i.e. invokable through Juggernaut.set_channels), and
therefore won’t be added to any classes which include the Juggernaut
module as instance methods. Is that what you wanted?

Basically, with your current code, the value of ‘self’ at the point of
execution for ‘Juggernaut.set_channels’ is the module Juggernaut,
which doesn’t have any variable or method ‘session’. The ‘session’
variable or method I’m guessing that you’re after is the one available
in ActionController::Base, and all subclasses. David Black’s book
explains this very well, and I can highly recommend it if you want to
understand how classes, modules, objects and methods interact.

Typically in a plugin you might do something like this (this could all
be in init.rb, not that such is good style but it should work):

module Juggernaut
def set_channels(chan) # note - no ‘self’
sessions[:juggernaut_channels] = chan

ActionController::Base.send(:include, Juggernaut)

At this point, once the plugin is loaded, all of your controllers have
a ‘set_channels’ instance method available, so you can do:

class MyController < ApplicationController
def some_action
# … stuff…
# … other stuff…


  • james

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs