## 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
You need to create an account or log in to post comments to this site.