Rails - How to use a Helper Inside a Controller

前端 未结 8 1229
生来不讨喜
生来不讨喜 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 15:46

    You can use

    • helpers.<helper> in Rails 5+ (or ActionController::Base.helpers.<helper>)
    • view_context.<helper> (Rails 4 & 3) (WARNING: this instantiates a new view instance per call)
    • @template.<helper> (Rails 2)
    • include helper in a singleton class and then singleton.helper
    • include the helper in the controller (WARNING: will make all helper methods into controller actions)
    0 讨论(0)
  • 2020-11-29 15:47

    In Rails 5+ you can simply use the function as demonstrated below with simple example:

    module ApplicationHelper
      # format datetime in the format #2018-12-01 12:12 PM
      def datetime_format(datetime = nil)
        if datetime
          datetime.strftime('%Y-%m-%d %H:%M %p')
        else
          'NA'
        end
      end
    end
    
    class ExamplesController < ApplicationController
      def index
        current_datetime = helpers.datetime_format DateTime.now
        raise current_datetime.inspect
      end
    end
    

    OUTPUT

    "2018-12-10 01:01 AM"
    
    0 讨论(0)
  • 2020-11-29 15:48
    class MyController < ApplicationController
        # include your helper
        include MyHelper
        # or Rails helper
        include ActionView::Helpers::NumberHelper
    
        def my_action
          price = number_to_currency(10000)
        end
    end
    

    In Rails 5+ simply use helpers (helpers.number_to_currency(10000))

    0 讨论(0)
  • 2020-11-29 15:50

    One alternative missing from other answers is that you can go the other way around: define your method in your Controller, and then use helper_method to make it also available on views as, you know, a helper method.

    For instance:

    
    class ApplicationController < ActionController::Base
    
    private
    
      def something_count
        # All other controllers that inherit from ApplicationController will be able to call `something_count`
      end
      # All views will be able to call `something_count` as well
      helper_method :something_count 
    
    end
    
    0 讨论(0)
  • 2020-11-29 15:59

    My problem resolved with Option 1. Probably the simplest way is to include your helper module in your controller:

    class ApplicationController < ActionController::Base
      include ApplicationHelper
    
    ...
    
    0 讨论(0)
  • 2020-11-29 16:01

    In general, if the helper is to be used in (just) controllers, I prefer to declare it as an instance method of class ApplicationController.

    0 讨论(0)
提交回复
热议问题