Rails - How to use a Helper Inside a Controller

前端 未结 8 1231
生来不讨喜
生来不讨喜 2020-11-29 15:01

While I realize you are supposed to use a helper inside a view, I need a helper in my controller as I\'m building a JSON object to return.

It goes a little like this:

8条回答
  •  清酒与你
    2020-11-29 16:05

    Note: This was written and accepted back in the Rails 2 days; nowadays grosser's answer is the way to go.

    Option 1: Probably the simplest way is to include your helper module in your controller:

    class MyController < ApplicationController
      include MyHelper
    
      def xxxx
        @comments = []
        Comment.find_each do |comment|
          @comments << {:id => comment.id, :html => html_format(comment.content)}
        end
      end
    end
    

    Option 2: Or you can declare the helper method as a class function, and use it like so:

    MyHelper.html_format(comment.content)
    

    If you want to be able to use it as both an instance function and a class function, you can declare both versions in your helper:

    module MyHelper
      def self.html_format(str)
        process(str)
      end
    
      def html_format(str)
        MyHelper.html_format(str)
      end
    end
    

    Hope this helps!

提交回复
热议问题