Some useful text helpers in Rails (Part – 1)
One of the most important features of Rails is it’s rich helper. Sometimes these are lifesavers because you don’t have to write your own code and very useful if you can use it in a clever way. While developing scrumpad ( scrumpad ) I found many places where texts need to be formatted and Rail’s helper came like a great boon. Let’s share some helpers!
Suppose your text contains both URL and email. auto_link will convert it to as links.
auto_link(“Go to www.scrumpad.com and meet email@example.com”)
It will place links automatically at the appropriate places. If you want to make the sites as url but not the mail, you can pass the option too like:
auto_link(“Go to www.scrumpad.com and meet firstname.lastname@example.org” , :link=>:urls)<p></p><p>auto_link(“Go to www.scrumpad.com and meet email@example.com” , :link=>:email_address)</p>
While providing alternate colors for tables for style purpose, we often put logic in the code to determine the even and odd row and places the color alternatively. This can be handled by a nice helper named “cycle”
suppose you have two CSS classes named “even” and “odd”. You can make the alternate rows to alternate colors by:
<tr class=”<%= cycle(“even”, “odd”)>”<td>Data</td> </tr>
Yes! You can guess it by its name. If you want to wrap a long line with (or without) a specified width you just call this helper.
word_wrap(“A brown colored fox jumped over the lazy dog”, :line_width=>5)
At times we wish to show the users a part of our long text and replace the lest with “…”. Rails make it easy for us as usual.
truncate(“Scrumpad, an agile project management tools by Code71”, 19)
The output will be something like “Scrumpad, an agile…”
If you want to provide your text instead of “…” you should write it as:
truncate(“Scrumpad, an agile project management tools by Code71”, 19, “….(More)”)
The output will be like “Scrumpad, an agile…(More)”
That’s all for today. I will come back to you guys with more. In the meantime, you can try these out (If you haven’t tried these yet 🙂 )
Contributor: Fuad Bin Omar, COO, Nascenia