我目前正在开发一个CMS,并想在URL中以一种很好的方式编码特殊字符。我不想使用Rack::Utils.escape。
有没有很酷的宝石可供选择?
诚挚的问候
发布于 2009-12-03 04:01:16
看看stringex gem here,它甚至可以在没有rails的情况下使用,但是包含了一些东西来使它更容易使用(有rails)。
发布于 2009-12-03 01:06:58
Ruby的CGI库应该可以满足您的需求:
url_encoded_string = CGI::escape("'Stop!' said Fred")
# => "%27Stop%21%27+said+Fred"请参阅http://ruby-doc.org/core/classes/CGI.html
发布于 2009-12-04 06:59:17
嗯,我通常使用一种方便的定制方法,称为String.to_slug。我希望你会发现它是有用的。
调用/lib/to_slug.rb并将其包含在一个初始化器中,或者仅将其包含在生成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
endhttps://stackoverflow.com/questions/1834332
复制相似问题