Reputation: 7866
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?
Upvotes: 0
Views: 2241
Reputation: 37507
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.
Upvotes: 6
Reputation: 25757
How about this:
def clean_name(name)
name.gsub(/[.\/,&()]/, '').gsub(/[\s\-]+/, '-')
end
Upvotes: 0