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

Rubify (See related posts)

Takes a string, such as a post title ("Rat Brains Fly Planes") and convets it into a ruby style variable name that can be used as an id or permalink url ("rat_brains_fly_planes")

Posted by Duane Johnson on rails list:
Here's the modified String class. This one
squeezes non-alphanumeric character sequences down to one underscore
and also makes sure it doesn't start or end with an underscore:

class String
  def rubify
    downcase.gsub(/\W/, ' ').squeeze.strip.gsub(' ', '_')
  end

  def rubify!
    replace rubify
  end
end

"!Hell93 o3#$@ the___re , dude".rubify
=> "hel93_o3_the_re_dude"

Luke Redpath suggested the following naming convention:
ID is short for identification the related verb of which is identify.

The appropriate verify_ macro would be verify_identity_of

A more conventional Ruby idiom would be to_id() (like to_s, to_i etc.).

"My, what a beautiful day!".to_id

=> "my_what_a_beautiful_day"


If thats not clear enough or possibly confusing with the normal use of id in a Rails app, perhaps to_identifier() instead.

Comments on this post

peter posts on May 06, 2006 at 20:47
One potential problem is that symbols and variables cannot start with a number.
usergenic posts on Mar 09, 2007 at 16:29
You're unnecessarily squeezing non-space characters-- you should change it to:
  downcase.gsub(/\W/, ' ').squeeze(' ').strip.gsub(' ', '_')


That way:
"wall" doesn't become "wal"

You need to create an account or log in to post comments to this site.


Click here to browse all 4858 code snippets

Related Posts