Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

where to put helper methods for controllers only?

Tags:

I am looking to write certain methods for processing strings, and other tasks that take place in numerous of my controllers. I know its bad practice to include helpers in your controller, so I was just wondering, where is the best place to put application wide methods used in controllers?

I realize some of you will say to put them in models, but you have to realize that not all my controllers have an associated model. Any and all input would be appreciated.

like image 926
flyingarmadillo Avatar asked Aug 14 '12 10:08

flyingarmadillo


People also ask

Where do I put controller helper?

If you need to use a method in the application scope then I would suggest that you keep those methods inside the application controller and in order to use them inside views.. declare those as helper methods. The problem is that if there are many helper methods, ApplicationController can become unwieldy.

How do you access the helper method in controller?

In the first version, you can just use html_format - you only need MyHelper. html_format in the second. This does not work when the helper method you want to use make use of view methods such as link_to . Controllers don't have access to these methods and most of my helpers use these methods.

Can we use helper method in controller Rails?

In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.

How do you use the helper method in Ruby on Rails?

A Helper method is used to perform a particular repetitive task common across multiple classes. This keeps us from repeating the same piece of code in different classes again and again. And then in the view code, you call the helper method and pass it to the user as an argument.


1 Answers

I tend to put them into helpers. The fact that they are included in views automatically haven't been a problem for me. You can also place them into something like app/concerns/ or lib/

I don't like cluttering ApplicationController with private methods because this often becomes a mess.

Example:

module AuthenticationHelper
  def current_user
    @current_user # ||= ...
  end

  def authenticate!
    redirect_to new_session_url unless current_user.signed_in?
  end
end

module MobileSubdomain
  def self.included(controller)
    controller.before_filter :set_mobile_format
  end

  def set_mobile_format
    request.format = :mobile if request.subdomain == "m"
  end
end

class ApplicationController
  include AuthenticationHelper
  include MobileSubdomain
end
like image 135
Simon Perepelitsa Avatar answered Sep 23 '22 14:09

Simon Perepelitsa