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. 

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…