Saturday, May 2, 2009

Pretty urls with name or title in ruby on rails

Hi folks,

Something on which is very old.. might not be very interesting for many of you who are into rails development. I am talking about the pretty-urls the SEO stuff(forget all this, it is for good readability of url).

So what my basic funda that i have gathered from last three years is that, every resource is identified by an identifier in rails(generally called id, in terms of database), but displaying the id doesn't sounds legal to me.. so to hide the ids and to have a nice looking readable

we can have title or name fields in the database's relation(table) and to make use of pretty urls, we make corresponding column like stripped_title or stripped_name.
create a file "make_pretty_url.rb" in initializers in config and append the following code.


puts "===================================================="
puts "Adding engine to make pretty url(s)"
puts "===================================================="
module ActiveRecord
class Base
after_create :make_or_update_pretty_url_name

def make_or_update_pretty_url_name
parent_column = nil
stripped_column = self.attributes.collect {|x| x.to_s.include?("stripped_") ? x : nil}.flatten.compact.first
if stripped_column
parent_column = stripped_column.gsub("stripped_","")
if self.send(parent_column)
self.send("#{stripped_column}=",stripp_it(self.send(parent_column)))
if self.class.find(:all, :conditions => ["#{stripped_column} = ?",self.send(stripped_column)]).length > 0
self.send("#{stripped_column}=","#{self.send(stripped_column)}-#{self.id.to_s}")
end
self.send("save")
end
end
end

def stripp_it(str)
str.strip.downcase.gsub(/[^a-z0-9]/,"-").gsub(/(-)+/,"-").gsub(/(-)+$/,"")
end
end
end


it will automatically create stripped_{column_name} and will take care of duplicates and instead of using find_by_id(), find_by_stripped_{column_name} will be used to get the resource and "make_or_update_pretty_url_name" method will also be available for any manual work too.

Hope this just adds in the knowledge base of stuff, and if there is anything about it, let me know through comments..

No comments:

Post a Comment

Sky diving! What it feels like.

Writing a new post after almost a year :) Penning it down here.. so that can relive that moment when i did the jump from 10000 feet up in...