在 Rails 中生成 slugs(人类可读的 ID)的最佳方法 [英] Best way to generate slugs (human-readable IDs) in Rails
本文介绍了在 Rails 中生成 slugs(人类可读的 ID)的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你知道,比如 myblog.com/posts/donald-e-knuth.
我应该使用内置的<代码>参数化方法?
插件呢?我可以想象一个插件可以很好地处理重复的 slug 等.这里有一些流行的 Github 插件——有没有人有使用它们的经验?
基本上,slug 似乎是一个完全解决的问题,我不会重新发明轮子.
解决方案
我使用了以下内容
- 翻译&--> "and" 和 @ --> "at"
- 不插入下划线代替撇号,所以 "foo's" --> "foos"
- 不包括双下划线
- 不会创建以下划线开头或结尾的 slug
例如:
<预><代码>>> 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?
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屋!
查看全文