简体   繁体   中英

Rails: Use helper_method from one controller in another

I have the following controller:

class FirstController < ApplicationController
  helper_method :contoller_method

private 
  def contoller_method
    "text"
  end
end

How can I use contoller_method in the view of another controller? Is there a best practice?

Place the method in the application_controller.rb . Then it'll be available to all your controllers.

If you only wanted to share it between two classes you could do something like this. Create a new controller called helper controller and have the First/Second controller inherit from it.

class FirstController < HelperController

end

class SecondController < HelperController

end

class HelperController < ApplicationController
  helper_method :contoller_method

  private 
    def contoller_method
      "text"
    end
end

Maybe this?

class FirstController
  include SomeConcern
end

class SecondController
  include SomeConcern
end

module SomeConcern
  def self.included(base)
    base.helper_method :controller_method
  end

  private 

  def controller_method
    "text"
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM