Never been to DZone Snippets before?

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

« Newer Snippets
Older Snippets »
Showing 1-8 of 8 total  RSS 

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

Rails route lets :id be a domain name

// Named route for an id that contains . characters, such as a domain name
// eg: http://myapp/domains/foobar.com

map.domain 'domains/:id', :controller => 'domains', :action => 'show', :requirements => { :id => /[a-zA-Z0-9\-\.]+/ }

exception_logger route

map.exceptions '/logged_exceptions/:action/:id', :controller => 'logged_exceptions', :action => 'index', :id => nil 

Named Routing in Rails (getting rid of the ids)

Lifted from Semergence
(http://www.semergence.com/archives/2005/12/01/10/02/32/)

In config/routes.rb:

map.projectproject/:projtitle’ :controller =>project’, :action =>show’


In app/controllers/project_controller.rb:
   def show
     @project = Project.find(:first,
                             :conditions => [’title = ?’,params[:projtitle]])end


Or something like that. Assuming your project titles are unique. Then
you can also use project_url (since you have map.project in routes.rb)
for urls in your views, e.g.

   <% for project in @projects %>
   <%= link_to project.title,
               project_url(:projtitle => project.title) %>
    …
   <% end %>

Alternative Default Routes

I prefer :controller/:id/:action formatted URIs to :controller/:action/:id. For instance, "people/56/edit" to "people/edit/56". This is a simple matter of taste and has no real benefits other than being a bit more intuitive to certain brains.

It's also a bit harder to do than you might expect. You need to replace the default :controller/:action/:id route with the following:

map.connect ':controller/:action', 
            :requirements => { :action => /\D+/ }

map.connect ':controller/:id/:action',
            :action => 'show',
            :requirements => { :id => /\d+/ }


This will result in the following URIs for the basic set of CRUD actions generated by default:

/people/         (:action => 'index')
/people/new
/people/create
/people/56/      (:action => 'show' by default)
/people/56/edit
/people/56/remove
/people/56/update


You could argue that the default route setup in Rails is a correct default because it's a bit more simple to apply across all cases.

Create spiffy myhost/[keyword] type routing

Except that I can't figure out how to do it in routes. This is what I found.

In *config/routes/rb*, as the last route add:
 map.connect '*path', :controller => 'application', :action => 'handle_unrecog'


In *app/controllers/application.rb*, put this:
 def handle_unrecog
  #do something here, the path info is in the @params value
 end


One of my uses for this is for a del.icio.us type user viewing. IE: _http://del.icio.us/[user]_ but having it only valid for users.

I'd do something like this:
 def handle_unrec
  uname = @params['path'][0] #first part of the path
  user = User.find_by_login( uname )
  if user
   return render :controller => "user", :action => "show", :id => user
  else
   return render :controller => "user", :action => "notfound"
  end
 end


Yay!

Snippets' routes

These routes allow URLs like tags/whatever/whatever/whatever to put 'whatever', 'whatever', and 'whatever' into the @params[:tags] array, etc.

map.connect '', :controller => "posts", :action => "index"
map.connect 'tags/*tags', :controller => 'tag', :action => 'show'
map.connect 'user/:user', :controller => 'user', :action => 'show'
map.connect 'user/:user/tags/*tags', :controller => 'tag', :action => 'show'


Pretty archive URLs in Typo with Routes

Tobi posted this as a new URL scheme for Typo.

# allow neat perma urls
map.connect 'articles/:year/:month/:day', :controller  => 'articles', 
     :action => 'find_by_date', 
     :year => /\d{4}/, :day => nil, :month => nil
map.connect 'articles/:year/:month/:day/:title', :controller  => 'articles', 
     :action => 'permalink', :year => /\d{4}/
« Newer Snippets
Older Snippets »
Showing 1-8 of 8 total  RSS