DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Make Your Model Play Nice With SEO

01.09.2008
| 5514 views |
  • submit to reddit
        
## config/initializers/string_extensions.rb

require 'unicode'

class String
  def to_slug
    str = Unicode.normalize_KD(self).gsub(/[^\x00-\x7F]/n,'')
    str = str.gsub(/\W+/, '-').gsub(/^-+/,'').gsub(/-+$/,'').downcase
  end

  def numeric?
    if self =~ /^\d+$/
      self.to_i
    elsif self =~ /^\d+([,\.]\d+)?$/
      self.tr(',','.').to_f
    else
      false
    end
  end
end


## app/models/article.rb

# string :title
# text   :body
# string :permalink
class Article < ActiveRecord::Base
  before_save :set_permalink

  # article_path(@article)
  # >> /article/5
  # article_path(@article.permalink)
  # /article/pink-ferret
  def self.find(*args)
    if args.first.is_a?(String) and !args.first.numeric?
      find_by_permalink(args.shift,*args) or raise ActiveRecord::RecordNotFound
    else
      super
    end
  end

  # article_path(@article)
  # >> /article/5-pink-ferret
  def to_param
    "#{id}-#{permalink}"
  end

  private
  def set_permalink
    self.permalink = title.to_slug
  end
end
    

Comments

addie warner replied on Wed, 2009/09/23 - 6:46am

Hey!! Thanks for the share man..I had trouble in my model which was not so geling with the seo technique..My options failed so let it do it..Compatible Ink Cartridges