代码之家  ›  专栏  ›  技术社区  ›  brainfck

编码URL的最佳方法?

  •  1
  • brainfck  · 技术社区  · 16 年前

    我不想使用Rack::Utils.escape。

    已经有很酷的宝石了吗?

    顺致敬意,

    3 回复  |  直到 16 年前
        1
  •  3
  •   jacortinas    16 年前

    here ,它甚至可以在没有rails的情况下使用,但它包含一些东西,使它更易于使用(使用rails)。

        2
  •  1
  •   Lytol    16 年前

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

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

        3
  •  0
  •   kikito    16 年前

    嗯,我通常使用一种方便的定制方法,叫做 String.to_slug . 我希望你觉得它有用。

    调用此/lib/to_slug.rb并将其包含在一个初始值设定项中,或者仅将其包含在生成URL的模型中。

    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