user938363
user938363

Reputation: 10350

RAILS: session is not defined in a module included in application controller

In application controller, a module common_helper is included:

include Commonx::CommonxHelper

A method return_misc_definitions is defined in CommonxHelper:

def return_misc_definitions(which_definition)
      Commonx::MiscDefinition.where(:active => true, :for_which => which_definition, :token => session[:token])
end 
module_function :return_misc_definitions

Then in controller, the above method is called:

@item_category = Commonx::CommonxHelper.return_misc_definitions('wh_item_category')

However there is error in spec:

Failure/Error: @item_category = Commonx::CommonxHelper.return_misc_definitions('wh_item_category')

     NameError:
       undefined local variable or method `session' for Commonx::CommonxHelper:Module

The session is not defined! My understanding was that when a method was called from a controller, the session was available in the method since it has been included in application controller . Is this understanding correct?

Upvotes: 2

Views: 472

Answers (1)

Anthony E
Anthony E

Reputation: 11235

You're calling return_misc_definitions directly on the Commonx::CommonxHelper module rather than as an instance method of the controller. This is why you're getting an undefined variable error on session - the CommonxHelper itself has no knowledge of session, unless it is mixed in (via include) as an instance method within a context where session is defined.

Since you've included the module in your controller, the following should suffice:

@item_category = return_misc_definitions('wh_item_category')

Since you're not using return_misc_definitions as a module/class method, your module_function really isn't doing much here. You can safely remove it.

EDIT

Thinking about this more, I don't really think this module is necessary since it doesn't have a useful place outside the context of a controller. Why not just declare misc_definitions in ApplicationController, or better yet the specific controller that needs it. Perhaps in ItemsController or CategoriesController?

Upvotes: 4

Related Questions