Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-5

Rails - How to use a Helper Inside a Controller


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:

def xxxxx

   @comments = Array.new

   @c_comments.each do |comment|
   @comments << {
     :id => comment.id,
     :content => html_format(comment.content)
   }
   end

   render :json => @comments
end

How can I access my html_format helper?


Solution

  • 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