0

I want to format the names of manufacturers to use in the url.

Example: IN-X / P.S.M. International

I wrote a helper method as follows

def clean_name(name)
      fn = name.gsub(/[.\/,&()]/, '') #replace these characters with nothing
      fnn=fn.strip.gsub(/[\s]/,'-')   #replace the spaces between the words with hyphens
      fnnn = fnn.gsub(/--/,'-')       #replace double hyphens with single ones
end

I know there must be a better way to do this than I have above. Any more experienced programmers have some ideas?

0

2 Answers 2

6

If you're using Rails, you can simply do:

string.parameterize

This comes from ActiveSupport::Inflector. For even more sophisticated slugging, see ActsAsUrl. It can do the following:

"rock & roll".to_url => "rock-and-roll"
"$12 worth of Ruby power".to_url => "12-dollars-worth-of-ruby-power"
"10% off if you act now".to_url => "10-percent-off-if-you-act-now"
"kick it en Français".to_url => "kick-it-en-francais"
"rock it Español style".to_url => "rock-it-espanol-style"
"tell your readers 你好".to_url => "tell-your-readers-ni-hao"

There are several other options listed in the Permalinks and Slugs category in Ruby Toolbox.

1
  • Wow I wish I had asked this earlier. Thanks a lot Mark.
    – chell
    Feb 8, 2012 at 8:07
0

How about this:

def clean_name(name)
  name.gsub(/[.\/,&()]/, '').gsub(/[\s\-]+/, '-')
end
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.