Helper methods to be used in Controllers AND Views in Rails

久未见 提交于 2019-12-06 03:50:51

You can put it in the controller and call:

helper_method :my_method

from the controller.

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.

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.

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