Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Helper directory in rails

Will a file in helper directory included in all controllers?. I didn't find any good explanation regarding this. I have 2 custom directories in my controller( like admin, for normal user). Do I have same directory structure at my helper?. Is Helper name same as controller name only for readability?

like image 900
Aarthi Avatar asked Apr 24 '18 01:04

Aarthi


People also ask

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.

What are view helpers?

4.13. View Helpers. A view helper is typically a (relatively) simple PHP class whose goal is to render some part of a view. You can invoke view helpers from any view template. With view helpers, you can create reusable widgets (like menus, navigation bars, etc.)

Where are custom view helpers stored within a standard Rails app?

Custom helpers for your application should be located in the app/helpers directory.

What are helper methods?

A helper method is a small utility function that can be used to extract logic from views and controllers, keeping them lean. Views should never have logic because they're meant to display HTML. In addition, there's no way to test view logic, but if we extract this logic into methods it can then be tested.


2 Answers

By default all helper files under app/helpers are included in all controllers. As such, it doesn't matter how you structure what's inside helpers folder. If you really want to enforce controller to only include matching helper then set config.action_controller.include_all_helpers in config to false.

See comment section for details: https://github.com/rails/rails/blob/b5db73076914e7103466bd76bec785cbcfe88875/actionpack/lib/action_controller/metal/helpers.rb

like image 187
kasperite Avatar answered Sep 21 '22 11:09

kasperite


Helper is just a ruby module which is openly available for views and controllers. You should never keep your code in helper if you do not want it to expose to views.

If you want to use helper methods for all your controller and views. Then you can add methods to application helper and include it to application controller. However if you don't want to expose methods to views, then you can use rails concerns. create a methods inside it and include it inside different controllers.

No helper do not name the same name only for readability. you still need to include inside your same name controller to call functions if you want to use it inside controller. But you can still use inside views methods with same name.

like image 43
Romanch Sharma Avatar answered Sep 22 '22 11:09

Romanch Sharma