Friday, January 29, 2010

Awesome Taxonomy module for categorise content in drupal

Taxonomy is pretty cool for creating categories in drupal. You can create multiple categories and sub categories for each node type. These categories are applied to the partucalar nodes as you mention. So the same category set can be set to multiple content types and also each content type have multiple categories lists. See all about taxonomy at http://groups.drupal.org/taxonomy

A small Tip

A small tip to call methods dynamically using Ruby's send method.

["foo", "bar"].each do |method|
MyClass.send(method)
end

The above code is same as calling MyClass.foo and MyClass.bar.

Make your rails application DRY with constants

Constants help with consistency, they easily allow you to keep your code DRY.
One of the ways I utitilise constants is to standardise the date formatting I use across an app.
For example, in environment.rb I will create a module to contain my date format constants:

module Dates
DATE_FORMAT = "%d% %b %Y"
DATE_TIME_FORMAT = "#{DATE_FORMAT} %H:%M"
end

The module just groups them nicely together. To use the constants I will write the following:

@object.created_at.strftime(Dates::DATE_FORMAT)
@object.created_at.strftime(Dates::DATE_TIME_FORMAT)

Remember you will need to restart your server after making any changes to environment.rb

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;
}