Ruby On Rails, Design, Simplicity, Web 2.0, Ajax, Mac and Tons of Pizza.

Nov 26

Plugin: create better urls with has_wfid

Posted by Sandro Paganotti in Ruby on Rails - comments are closed digg this add to delicious

I’ve wrote a small plug-in that will help you turn your RESTful routes from this:

/projects/1/milestones/3

to:

/projects/1-install-ubuntu/milestones/3-order-a-free-cd

The implementation is quite simple, you’ve just to add a line to the model file and specify which fields you want to use to create the url


class Project < ActiveRecord::Base
has_many :milestones
has_wfid :fields=>%w(title)
end

class Milestone < ActiveRecord::Base
belongs_to :project
has_wfid :fields=>%w(title)
end

and then use wfid instead of id while creating urls in your controller:


milestone_url(:project_id=> current_milestone.project.wfid, :id=>current_milestone.wfid ) 

That’s it !

Now let’s take a look at the main method inside the plug-in (I’ve already wrote a tutorial that explains how to create an acts_as plugin so please refer to it if you need more detailed info) :


def has_wfid(options = {})

 class_eval <<-END
     define_method("wfid") do
       val = (#{options[:fields].join(" + ")}).gsub(/\W+/, ' ').strip.downcase.gsub(/\ +/, '-')
       val.blank? ? id.to_s : id.to_s + "-" + val
     end
 END

end

Hope you’ll find this useful!

ps: you can find the zipped plug-in here while I’m working on a dedicated svn repository.

Comments

  • Jeremy Weiskotten

    Posted on November 26

    Thanks for contributing to the Rails community! This looks similar to PermalinkFu, acts_as_urlnameable, acts_as_slugable, and acts_as_friendly_param. Is there something that you did differently or better than the existing plugins?
  • Sandro

    Posted on November 26

    I really don't know if I'd done something different (or better) than the plug-ins you list :) I've wrote has_wfid to meet my developing needs and I shared it following the Rails philosophy.
  • Christoph Olszowka

    Posted on December 13

    Hi there, I think this makes things more complicated than they should be: Since the default RESTful url helpers use the models to_param-method, which by default returns the record's id, you can implement a custom to_param method in your model, which will result in projects/1-installing-ubuntu etc. Greetings
  • Jerome

    Posted on January 05

    Your wfid method can't handle accents. This string method does: http://snippets.dzone.com/posts/show/4948

Post a comment

Categories:

Tags:

Powered by Mephisto, Valid XHTML 1.1, Valid CSS - Supported by Wave Factory