Ever thought of organizing your code in more than one files , rather writing all in one place.
Sometime, you want a method accessible to all your controller. Solutions to this is:
1) ApplicationController
2)Copy the same methods in each controller specific helper file i.e REPEAT YOURSELF, which go against the rails philosophy of DRY( Do Not Repeat Yourself)
3) Custom Helpers
Out of aforementioned options, very first is liked to buzz your mind first. But sooner or later you'll find your single application Controller file very cluttered. so, how to get rid of it and divide your files in more cleaner way?Custom Helper comes to your rescue.
How to create Custom Helper(module)
Create a new file in Helper Directory and name is as my_module_name_helper.rb.
Remember my_module_name should be same as your module name.
Inside the file, structure your code as follow:
module MyModuleNameHelper
def myMethod1
end
def myMethod2
end
......
..
end
Once done, you need to tell controllers about your newly made helper file.
Open your application_controller.rb file inside controllers folder and this line
helper :my_module_name, :my_second_module_name
OR
helper :all # To include all helpers file. :D
more on this here
Sometime, you want a method accessible to all your controller. Solutions to this is:
1) ApplicationController
2)Copy the same methods in each controller specific helper file i.e REPEAT YOURSELF, which go against the rails philosophy of DRY( Do Not Repeat Yourself)
3) Custom Helpers
Out of aforementioned options, very first is liked to buzz your mind first. But sooner or later you'll find your single application Controller file very cluttered. so, how to get rid of it and divide your files in more cleaner way?Custom Helper comes to your rescue.
How to create Custom Helper(module)
Create a new file in Helper Directory and name is as my_module_name_helper.rb.
Remember my_module_name should be same as your module name.
Inside the file, structure your code as follow:
module MyModuleNameHelper
def myMethod1
end
def myMethod2
end
......
..
end
Once done, you need to tell controllers about your newly made helper file.
Open your application_controller.rb file inside controllers folder and this line
helper :my_module_name, :my_second_module_name
OR
helper :all # To include all helpers file. :D
No comments:
Post a Comment