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
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
I'm not familiar with Ruby - can you use Javascript encodeURI() or encodeComponentURI() methods?
Ruby's CGI library should do what you need:
url_encoded_string = CGI::escape("'Stop!' said Fred")
# => "%27Stop%21%27+said+Fred"
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).
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