Helper methods to be used in Controllers AND Views in Rails

流过昼夜 提交于 2019-12-07 18:08:53

问题


I understand I can put a helper method in a Helper class inside the helper folder in Rails. Then that method can be used in any view. And I understand I can put methods in the ApplicationController class and that method can be used in any controller.

Where's the proper place to put a method that is frequently used in both controllers and views?


回答1:


You can put it in the controller and call:

helper_method :my_method

from the controller.




回答2:


You can put a method in a controller and then call helper_method in the controller to indicate that this method is available as if it were in a helper too.

For example:

class ApplicationController

  helper_method :this_is_really_useful

  def this_is_really_useful
    # Do useful stuff
  end

This method will then be available to all controllers and to all views.




回答3:


I put helpers like the ones you describe in a module in my lib/ directory. Given some MyApp application, this would go in app/lib/my_app/helpers.rb and look like

module MyApp
  module Helpers
    extend self

    def some_method
      # ...
    end 

  end
end

Next, you must require this module. Create a new initializer at config/initializers/my_app.rb that looks like

require 'my_app'

and make sure config.autoload_paths contains your lib/ directory in config/application.rb.

config.autoload_paths += Dir["#{config.root}/lib",
                             # other paths here...
                            ]

Finally, include the module wherever you want to use it. Anywhere.

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base

  include MyApp::Helpers

app/helpers/application_helper.rb

module ApplicationHelper
  include MyApp::Helpers

I think this is a cleaner, more testable approach to managing reusable helpers throughout your application.



来源:https://stackoverflow.com/questions/18775055/helper-methods-to-be-used-in-controllers-and-views-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!