开发者

Accessing Rails helpers from a presenter/module?

开发者 https://www.devze.com 2023-03-27 08:36 出处:网络
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.

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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号