Ruby post title to slug

后端 未结 5 1164
轮回少年
轮回少年 2020-12-23 19:21

How should I convert a post title to a slug in Ruby?

The title can have any characters, but I only want the slug to allow [a-z0-9-_] (Should it allow an

5条回答
  •  情深已故
    2020-12-23 20:13

    to_slug is a great Rails plugin that handles pretty much everything, including funky characters, but its implementation is very simple. Chuck it onto String and you'll be sorted. Here's the source condensed down:

    String.class_eval do
      def to_slug
        value = self.mb_chars.normalize(:kd).gsub(/[^\x00-\x7F]/n, '').to_s
        value.gsub!(/[']+/, '')
        value.gsub!(/\W+/, ' ')
        value.strip!
        value.downcase!
        value.gsub!(' ', '-')
        value
      end
    end
    

提交回复
热议问题