A Ruby on Rails Guide to Helper Methods
I’m back after a nice holiday week and a subject that I wanted to write about today is helper methods. I wrote about public v private methods two weeks ago and helper methods kept coming up during my research. I thought it may be fitting to discuss the use of them today because as the name entails, they can be helpful.
Let us first take a look at what a helper method is. a helper method is a great way to save time and not have to reuse the same code over and over. Ruby on Rails is a bit of black magic for those who are new to it. It has a lot of built in functionality that requires a bit of digging. One of these examples comes in the fact that Ruby on Rails has built in helper methods that you don’t even need to write! Some can convert numbers into words whereas others have the ability to convert numbers to currency (I have used this a few times on a couple projects). If you are curious about built in helpers, here is the documentation. I was pretty surprised at how many are actually built in but it shouldn’t shock me considering how detailed Ruby on Rails can get. But we will circle back. A helper method can be one that is already defined by Ruby on Rails or designed by you as well. These can be helpful if you want to display something multiple times without having to rewrite it each time. A place that can be very helpful for this would be if you require logging in to your site, instead of rewriting some way to check if the user has logged in, you can write it once and use it for each page that a user must be logged in to view. You can even combine two helper methods to create a more in depth helper method. here’s an example:
We have two helper methods here. Both are slimming down how I can call for a price on each class. But when I combine them, I can do something pretty cool like this:
This might seem fairly basic but you can see the endless possibilities when you can start stacking these helper methods.
This is a pretty basic introduction to helper methods, I am sure you can find some more detailed instructions on how to use them best but I feel like this is a great place for beginners to start understanding how “helpful” these can be. As always, happy coding friends!