This is a quick and simple intro to using helper methods in Ruby on Rails. I'll demonstrate some simple and tidy techniques for using html, strings and ruby together.
What is a helper?
Helpers are basically small snippets of code that can be called in your views to help keep your code DRY - i.e. Any code that you are repeating regularly can most likely be moved into a helper.
Using helpers is simple, each controller has it's own helper file or you can write helpers in the application helper file if it will be used across the entire application. For example a pagination helper might go in there.
Helpers look like this:
def my_helper
some code
end
You can then use it in your view with:
<%= my_helper %>
How to use variables with helpers
You can pass variables into them exactly how you might expect:
def my_helper(condition)
if condition
"do this"
else
"do that"
end
end
You also might like to pass in a hash, it's as easy as:
def my_helper(opts={})
{:arg_one => 'foo', :arg_two => 'bar'}.merge!(opts)
end
You can refer to the hash methods passed in with something like:
def my_helper(opts={})
"output something" if opts[:method_passed_in] == "foo"
end
I quite like to set defaults so that my helpers can work without forcing you to pass variables, e.g.:
def my_helper(variable = nil)
if variable
"do this"
else
"do that"
end
end
Basically variable will be nil unless it's passed in when the helper is called.
String manipulation
These string manipulation methods methods aren't exclusive to helpers, and in fact neither are the previous examples of passing variables and hashes. However, helpers are as good a place as any to demonstrate.
By default helper, methods expect ruby code. So in order to enter html or any general string output you need to stick it in quotes. As easy as:
def my_helper
"<p>Hello world</p>"
end
If you want to stick some ruby/rails magic inside the string then you can do something like the following:
def my_helper
"<p>Visit my #{link_to("website", "http://paulsturgess.co.uk")}</p>"
end
Note that you must use double quotes and not single ones to take advantage of #{ruby code goes here}
Often your helper will have some conditions in it that mean you will build the html output over several lines, so the following might be handy:
def my_helper
html = ""
if some_condition
html << "<p>Visit my #{link_to("website", "http://paulsturgess.co.uk")}</p>"
else
html << "<p>Visit some other #{link_to("website", "http://google.co.uk")}</p>"
end
end
Note that helpers will return the value of the last line evaluated.
Now sometimes I find I want to stick quite a few lines of html in a helper and rather than writing out << each time, there's a really tidy way of achieving this:
def my_helper
html = ""
html = <<HTML
<ul>
<li>lots</li>
<li>of</li>
<li>html</li>
</ul>
HTML
end
Note the final HTML line must not be indented. Unfortunately the syntax highlighter i'm using on this site doesn't understand this technique but Textmate's syntax highlighting will pick it up which is nice.
Hopefully that gives a quick and easy introduction to using helpers in Ruby on Rails.
About Paul
Paul works for Kyan web design agency in Surrey, UK as a Ruby on Rails developer.
Follow Paul on Twitter
Email: paulsturgess [at] gmail.com
Comments...
nice intro!! cheers :-)
sal at 19 Jul 07 at 21:44
Thanks. Best bit of Helper 101 I've found. Much appreciated.
Matt Johnson at 25 Jan 09 at 07:54
Thank you so much.
Such simple things are so difficult to find out :-)
James West at 27 Jan 09 at 20:49
Where is this << functionality documented? "<<" is unsearchable in google, for example. I'm interested in an example with several lines of HTML elements interspersed with ruby conditional logic.
Thanks!
ZardozVersusKPAX at 23 Feb 09 at 17:44
Thks ........you done a nice work
Sunny Tholar at 02 Jan 10 at 03:40
Ya its very helpfull to know about the helpers !!!
But I need more stuff to have more details on it
Minal Jain at 05 Jan 10 at 23:38
This was very helpful. Oddly, documentation about helpers is scarce and what there is is pitched at an advanced level. This got me started. Thanks.
Ian James at 14 Jan 10 at 16:29
nice explanation . Thanks
----------------------
http://pvtlink.com
Hide image or file source
pvtlink at 17 Mar 10 at 05:29
You know you can just use <<-HTML
with a hyphen immediately following the left arrows and immediately preceeding the heredoc token. And indent the HTML closing all you want. That way your code remains more readable.
HTML
And for ZardozVersusKPAX, its called Heredoc syntax.
mgadda at 29 Jun 10 at 17:27
Nice and good post. Thanks. very much
Mena at 19 Jul 10 at 04:47
Will this work??????????
inside helperfile
def name
@name=User.first
end
inside controller
def controllername
name.fieldname
end
Jeffrey at 05 Aug 10 at 02:30
about the previous coding, this is how it works
inside helperfile>>>>>
def show_header_footer
@name=User.first
end
inside Prawn file>>>>>>>>>>>
show_header_footer
user_name = @name
Jeffrey at 05 Aug 10 at 04:49
You should note that the methods defined in the helper file are available to only the view, while helper methods defined in the controller can be called both in the controller and in the view. At least...that's what my experience leads me to believe.
Liam at 13 Sep 10 at 08:42
nice work...
ariv at 08 Oct 10 at 06:37
nice tutorial...but can v use helpers in controllers ?
Rushabh Hathi at 26 Jan 11 at 10:15
Thanks, this was great. I've been a Django guy for a long time, but I'm trying Ruby on Rails.
John Ankarström at 28 Jan 11 at 10:29
its a good and useful article.thanks......
chaitu at 30 Jan 11 at 23:32
Why would my helper which is like this
def actions_menu(model)
html = "<div>This is my model #{model}"</div>
html
end
would be printing
<div>This is my model product </div>
in the browser, I mean is printing the tags!
I invoked the helper like this <%=menu_actions(product)%>
alberto at 01 Mar 11 at 15:08
Thanks....for your tutorial
Sourav at 01 Apr 11 at 21:35
Hello.........Can helper method can be used at controller side
Harish at 01 Jun 11 at 21:04
Thanks a lot!!!! Learned so much..finally piecing everything together
Joshua C. at 07 Oct 11 at 20:48
Thanks
Virtual at 16 Jan 12 at 14:55
def my_helper
"
Visit my #{link_to("website", "http://paulsturgess.co.uk")}
"end
The above code does not produce a link tag.
Is there any error ?
Hare Ram Rai at 02 Feb 12 at 11:42
Got something to say?