tips for Ruby/Rails newbies

I shared some tips with a colleague who is relatively new to rails, and thought I’d post them here too.


##before:
content_tag :div, @event.description_html unless @event.description_html.to_s.blank?

## better:
# blank works on nil, string, array, and hash. It's a rails thing from ActiveSupport.
content_tag :div, @event.description_html unless @event.description_html.blank?

## best:
#But even better is to use the special #{attribute}? methods which we get with Rails 2. These basically just call !#{attribute}.blank?
content_tag :div, @event.description_html if @event.description?

the returning method is also handy at times… also from ActiveSupport. Here is an abstracted example from a rails helper: I’m not sure why yet, but returning doesn’t seem to work with strings


## before:
html = "" 
html += "some stuff" if some_condition
html += "123" 
html

## after:
returning [] do |html|
  html <<  "some stuff" if some_condition
  html << "123" 
end.join("\n")


and also the pluralize method is part of ActionView::Helpers


## before:
 def people_or_person(count)
   (count == 1) ? 'person' : 'people'
 end
## after:
pluralize count, "person" 

using case…



## before:
   word.each_char do |x|
     if ((x =~ /[a-zA-Z]/) == 0)
       str <<  "[#{x.to_s.downcase}#{x.to_s.upcase}]" 
     else
       str << "[#{x}]" 
     end
   end

## after:
   word.each_char do |x|
     case x
     when /[a-zA-Z]/
       str << "[#{x.to_s.downcase}#{x.to_s.upcase}]" 
     else
       str << "[#{x}]" 
     end
   end


using map_with_index (or the closest thing we have in Ruby 1.8) aka collect_with_index


## before:
   roles = []
   @events_summary[:role_groups].each_with_index do |role, idx|
     roles << [role[:for], idx]
   end
   roles

## after:
   require 'enumerator'
   @events_summary[:role_groups].enum_with_index.map{ |role, idx| [ role[:for], idx ] }

## Ruby 1.9:
   @events_summary[:role_groups].map.with_index{ |role, idx| [ role[:for], idx ] }

Leave a Reply