Jay Levitt
Jay Levitt

Reputation: 1720

Accessing Rails helpers from a presenter/module?

There are many questions about accessing Rails helpers from a model, all of which rightfully state that the answer is not to do that. This is not that question.

I have some fairly complex controller and view code that I want to abstract into a presenter class. But that class isn't a descendant of ApplicationController. How can I get access to, say, devise's current_user?

Upvotes: 2

Views: 2544

Answers (1)

Jay Levitt
Jay Levitt

Reputation: 1720

It appears there's no "official right" way to do this at the moment. Two possibilities:

  1. It's hacky, but you can store the current controller in ApplicationController, and reference it in your presenters to get at the helpers:

    class ApplicationController < ActionController::Base
      prepend_before_filter { @@current_controller = self }
    end
    
    class YourPresenter
      def current_user
        ApplicationController.current_controller.current_user
      end
    end
    
    1. Jeff Casimir is working on a great Decorator/Presenter gem called draper that encapsulates the whole idea:

https://github.com/jcasimir/draper

Upvotes: 3

Related Questions