Using helpers in model: how do I include helper dependencies?

后端 未结 6 873
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 13:37

I\'m writing a model that handles user input from a text area. Following the advice from http://blog.caboo.se/articles/2008/8/25/sanitize-your-users-html-input, I\'m cleani

相关标签:
6条回答
  • 2020-11-27 14:10

    This works better for me:

    Simple:

    ApplicationController.helpers.my_helper_method
    

    Advance:

    class HelperProxy < ActionView::Base
      include ApplicationController.master_helper_module
    
      def current_user
        #let helpers act like we're a guest
        nil
      end       
    
      def self.instance
        @instance ||= new
      end
    end
    

    Source: http://makandracards.com/makandra/1307-how-to-use-helper-methods-inside-a-model

    0 讨论(0)
  • 2020-11-27 14:13

    To access helpers from your own controllers, just use:

    OrdersController.helpers.order_number(@order)
    
    0 讨论(0)
  • 2020-11-27 14:14

    Just change the first line as follows :

    include ActionView::Helpers
    

    that will make it works.

    UPDATE: For Rails 3 use:

    ActionController::Base.helpers.sanitize(str)
    

    Credit goes to lornc's answer

    0 讨论(0)
  • 2020-11-27 14:27

    I wouldn't recommend any of these methods. Instead, put it within its own namespace.

    class Post < ActiveRecord::Base
      def clean_input
        self.input = Helpers.sanitize(self.input, :tags => %w(b i u))
      end
    
      module Helpers
        extend ActionView::Helpers::SanitizeHelper
      end
    end
    
    0 讨论(0)
  • 2020-11-27 14:32

    If you want to use a the my_helper_method inside a model, you can write:

    ApplicationController.helpers.my_helper_method
    
    0 讨论(0)
  • 2020-11-27 14:35

    This gives you just the helper method without the side effects of loading every ActionView::Helpers method into your model:

    ActionController::Base.helpers.sanitize(str)
    
    0 讨论(0)
提交回复
热议问题