views:

107

answers:

4

Hi,

I am currently developing a CMS and want to encode special chars in the URL in a nice way. I don't want to use Rack::Utils.escape.

Is there already a cool gem available?

Best regards

A: 

I'm not familiar with Ruby - can you use Javascript encodeURI() or encodeComponentURI() methods?

Mark Cooper
A: 

Ruby's CGI library should do what you need:

url_encoded_string = CGI::escape("'Stop!' said Fred")
# => "%27Stop%21%27+said+Fred"

See http://ruby-doc.org/core/classes/CGI.html

Lytol
dude, that is a really ugly URL and I already explained that I don't want to use this - Rack::Utils.escape does the same as CGI
brainfck
It's not the library's fault that the URL is ugly. You want special characters encoded in the URL, it's going to be ugly.
ScottJ
I'm not sure what you are looking for then -- encoding in a "non-ugly way" doesn't really mean anything to me. Can you give examples?
Lytol
for example that a "ö" gets replaced with "oe"
brainfck
+1  A: 

Look at the stringex gem here, it can be used even without rails, but contains some stuff to make it easier to use(with rails).

jacortinas
A: 

Well, I normally use a handy custom-made method called String.to_slug. I hope you find it useful.

Call this /lib/to_slug.rb and include it in one initializer, or include it only on the model that generates the urls.

String.class_eval do

  #converts accented letters into ascii equivalents (eg. ñ becomes n)
  def normalize
    #this version is in the forums but didn't work for me
    #chars.normalize(:kd).gsub!(/[^\x00-\x7F]/n,'').to_s
    mb_chars.normalize(:d).gsub(/[^\x00-\x7F]/n,'').to_s
  end

  #returns an array of strings containing the words on a string
  def words
    gsub(/\W/, ' ').split
  end

  #convert into a nice url-ish string
  def to_slug(separator='-')
    strip.downcase.normalize.words.join(separator)
  end

end
egarcia