Over a million developers have joined DZone.

Make Your Model Play Nice With SEO

·

## 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
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}