24 December 2009

Some useful text helpers in Rails (Part - 1)

One of the most important features of Rails is it’s rich helper. Sometimes these are life savers 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!

1.  auto_link

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 fuad@code71.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 fuad@code71.com” , :link=>:urls)

auto_link(“Go to www.scrumpad.com and meet fuad@code71.com” , :link=>:email_address)

 

2. cycle

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>

3. word_wrap

Yes! You can guess it by it’s 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)

4.  truncate

At times we wish to show the users a part of our long text and replace the lest with “…”. Rails makes it easy for us as usual.

truncate(“Scrumpad, a agile project management tools by Code71”, 19) 

Output will be something like  “Scrumpad, an agile…”

If you want to provide your text instead of “…” you should write it as:

truncate(“Scrumpad, a agile project management tools by Code71”, 19, “….(More)”) 

Output will be like “Scrumpad, an agile…(More)”

That’s all from 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 :-) )

1 comment:

we4tech said...

this is indeed a good post :)_) i really like it :)_)