在 Rails 中生成 slugs(人类可读的 ID)的最佳方法 [英] Best way to generate slugs (human-readable IDs) in Rails

查看:52
本文介绍了在 Rails 中生成 slugs(人类可读的 ID)的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你知道,比如 myblog.com/posts/donald-e-knuth.

我应该使用内置的<代码>参数化方法?

插件呢?我可以想象一个插件可以很好地处理重复的 slug 等.这里有一些流行的 Github 插件——有没有人有使用它们的经验?

  1. http://github.com/rsl/stringex/tree/master
  2. http://github.com/norman/friendly_id/tree/master

基本上,slug 似乎是一个完全解决的问题,我不会重新发明轮子.

解决方案

我使用了以下内容

  • 翻译&--> "and" 和 @ --> "at"
  • 不插入下划线代替撇号,所以 "foo's" --> "foos"
  • 不包括双下划线
  • 不会创建以下划线开头或结尾的 slug
<预><代码>def to_slug#剥离字符串ret = self.strip#吹掉撇号回复!/['`]/,""# @ --> at, and & --> andret.gsub!/\s*@\s*/, " 在 "回复!/\s*&\s*/, " 和 "#用下划线替换所有非字母数字、下划线或句点回复!/\s*[^A-Za-z0-9\.\-]\s*/, '_'#将双下划线转换为单下划线回复!/_+/,"_"#去掉前导/尾随下划线回复!/\A[_\.]+|[_\.]+\z/,""回复结尾

例如:

<预><代码>>> s = "爸爸妈妈@home!"=>爸爸妈妈@home!">> s.to_slug> 妈妈和爸爸在家里"

You know, like myblog.com/posts/donald-e-knuth.

Should I do this with the built in parameterize method?

What about a plugin? I could imagine a plugin being nice for handling duplicate slugs, etc. Here are some popular Github plugins -- does anyone have any experience with them?

  1. http://github.com/rsl/stringex/tree/master
  2. http://github.com/norman/friendly_id/tree/master

Basically it seems like slugs are a totally solved problem, and I don't to reinvent the wheel.

解决方案

I use the following, which will

  • translate & --> "and" and @ --> "at"
  • doesn't insert an underscore in place of an apostrophe, so "foo's" --> "foos"
  • doesn't include double-underscores
  • doesn't create slug that begins or ends with an underscore


  def to_slug
    #strip the string
    ret = self.strip

    #blow away apostrophes
    ret.gsub! /['`]/,""

    # @ --> at, and & --> and
    ret.gsub! /\s*@\s*/, " at "
    ret.gsub! /\s*&\s*/, " and "

    #replace all non alphanumeric, underscore or periods with underscore
     ret.gsub! /\s*[^A-Za-z0-9\.\-]\s*/, '_'  

     #convert double underscores to single
     ret.gsub! /_+/,"_"

     #strip off leading/trailing underscore
     ret.gsub! /\A[_\.]+|[_\.]+\z/,""

     ret
  end

so, for example:


>> s = "mom & dad @home!"
=> "mom & dad @home!"
>> s.to_slug
> "mom_and_dad_at_home"

这篇关于在 Rails 中生成 slugs(人类可读的 ID)的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆