Plugin: create better urls with has_wfid
Posted by Sandro Paganotti in
Ruby on Rails -
comments are closed
/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
Sandro
Posted on November 26
Christoph Olszowka
Posted on December 13
Jerome
Posted on January 05