Saturday, July 29, 2006

Comparison of String with Integer failed

If you have code like

if @category_id >=1

then you will get the following error:

comparison of String with 1 failed

To fix the error modify the above code so it is something like:

if @category_id.to_i >=1

Custom URLs with routes.rb

Using the routes.rb file, we can create custom URLs. It is important to note that the following is valid :

map.connect ':permalink', :action=>'list', :controller=>'categories'

whereas the following are not valid:

map.connect ':permalink-:id', :action=>'list', :controller=>'categories'
map.connect ':permalink_id.html', :action=>'list', :controller=>'categories'
map.connect ':permalink-:id.html', :action=>'list', :controller=>'categories'

Calling a controller method from a view raises NoMethodError

If you put a custom function in application.rb or another controller and then try to access it from your view, you'll get the "No Method Error" similar to following:

NoMethodError in Categories#list
Showing app/views/categories/list.rhtml where line #23 raised:
undefined method `create_permalink' for #<#:0xb7931838>

The solution is to place the function as a helper function in the app/helpers/categories_helper.rb or app/helpers/application_helper.rb file.

URL Escape and URL Unescape

I find these functions really handy when having to escape or unescape URL:

def url_escape(string)
string.gsub(/([^ a-zA-Z0-9_.-]+)/n) do
'%' + $1.unpack('H2' * $1.size).join('%').upcase' ', '+')

def url_unescape(string)'+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/n) do

I usually place them in application.rb.

Calculating time difference

Here is a Ruby on Rails function I wrote that returns time difference in minutes. It can be easily modified to return time difference in seconds, hours etc.

def time_diff_in_minutes (time)
diff_seconds = ( - time).round
diff_minutes = diff_seconds / 60
return diff_minutes

Embedding and extracting primary key in a clean URL

Clean URLs are very important for search engines and for that reason I always prefer them.

A url of the form is better than

An even better form of the URL is where article-title represents the important keywords that appear in the title.

When using Ruby on Rails, you can create the permalink from title using the following function:

def create_permalink(string)
string.gsub(/([^ a-zA-Z0-9_.-]+)/n) do
'%' + $1.unpack('H2' * $1.size).join('%').upcase' ', '-').downcase


and you can extract the id from this permalink using a function given below:

def get_id_from_permalink(permalink)
@temp_array = permalink.split('-')
return id

Sunday, July 16, 2006

Ruby on Rails tips

Call a function before each method in a controller.
Define the function in application.rb and then edit your desired controller file and put the following
before_filter :application_essentials

eXTReMe Tracker