Helper Functions in Ruby on Rails
Helper functions are used to unclutter your Ruby code in Rails framework. We can show usefulness of Ruby Helper Functions by starting with Ruby code without helper being in place.
class MyController < ApplicationController
def index
@my_array = [1,2,3,4]
end
end
Now, let’s put a view that will display values from my_array on the web page.
<ul>
<% @my_array.each_with_index do |item, i|%>
<li> <%= i %> : <%=item.id.to_s%></li>
<%end%>
</ul>
Now, let’s add helper to our project to make displaying the list of time from my_array simpler for re-use and maintainability. This helper function will reside inside “app/helpers/list_helper.rb”
module ListHelper
def create_li (item, i)
${<li> <%= i %> : <%=item.id.to_s%></li>}
end
end
We can clean up our view with the following lines of code that makes our view more readable.
<ul>
<% @my_array.each_with_index do |item, i|%>
<li><%= create_li(item, i) %></li>
<%end%>
</ul>
Rails Helper are used to create more maintainable code base and to further separate work of the UI designer and Ruby developer. Rails suggests to read your code out loud and if something becomes less semantically attractive, then this part of the code should be converted into Ruby helpers. Helpers and Partials are similar concepts and both designed to accomplish pretty much same objective of code maintainability and encapsulation.