Rowandish
Rowandish

Reputation: 2735

Rails: Make Devise helpers available in modules (generically outside a controller)

I'm developing using Rails 4.1.

I have the following module (in app/policies/model_filters/helpers.rb:

module ModelFilters
  module Helpers
    def allow(record, action)
    end
  end
end

I included it in my app\controllers\application_controller.rb:

class ApplicationController < ActionController::Base
  include ModelFilters::Helpers

And in the class where I want to use them (app\bar\foo.rb):

class Foo
  include ModelFilters::Helpers

The methods are included correctly but Devise helpers seems not to be available in the module described above; when I start my spec test I get:

undefined local variable or method 'current_user' for #<Foo...
# ./app/policies/model_filters/helpers.rb:5:in `allow'
# ./app/bar/foo:13:in `recent'

Do you know how to make Devise helpers be seen in a module or, generically, outside a controller?

Thanks!

Upvotes: 0

Views: 1335

Answers (1)

philnash
philnash

Reputation: 73057

Devise helpers are only available within a controller because they only make sense within the context of an action being called.

If you think about your Foo class, what would current_user really mean? Within a controller, current_user is the user object that Devise can find from data stored in the session.

If you need to use a user object within a different class, it is best to pass the user to the class or method that you're calling.

Upvotes: 3

Related Questions