Thursday, January 28, 2010

Helpers usage in ROR

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.


def my_helper(opts={}) #args defined as hash
"output something" if opts[:method_passed_in] == "foo"
end

You can then use it in your view with:


<%= my_helper('foo') %>

Ruby on Rails User multiple layouts in single controller

Use multiple layouts in single controller using helpers, one layout per some actions and other for some actions etc..

layout :choose_layout

private
def choose_layout
if [ 'signup', 'login' ].include? action_name
'login'
else
'admin'
end
end

Alternate row colors for table rows in Ruby on Rails

Use the rails builtin helper "cycle" to add alternate row colors to the table rows in a loop.

<%- for item in @items do -%>

tr class="<%= cycle("even", "odd") %>"
... use item ...
/tr

<%- end -%>


Then in your stylesheet add below

tr.even td{
background-color:#CCC;
}

tr.odd td{
background-color:#EEE;
}