Ruby 帖子标题到 slug
我应该如何在 Ruby 中将帖子标题转换为 slug?
标题可以包含任何字符,但我只希望 slug 允许 [a-z0-9-_]
(它应该允许任何其他字符吗?)。
所以基本上:
- 所有字母都小写
- 将空格转换为连字符
- 删除无关的字符
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 any other characters?).
So basically:
- downcase all letters
- convert spaces to hyphens
- delete extraneous characters
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是铁轨吗? (在 Sinatra 中工作)
就是这样。对于更复杂的重击,请参阅 ActsAsUrl。它可以执行以下操作:
Is this Rails? (works in Sinatra)
That's it. For even more sophisticated slugging, see ActsAsUrl. It can do the following:
downcase
使其变为小写。strip
确保没有前导或尾随空格。第一个gsub
用连字符替换空格。第二个gsub
删除所有非字母非破折号非下划线字符(请注意,该集非常接近\W
但也包含破折号,这就是为什么此处已详细说明)。downcase
makes it lowercase. Thestrip
makes sure there is no leading or trailing whitespace. The firstgsub
replaces spaces with hyphens. The secondgsub
removes all non-alpha non-dash non-underscore characters (note that this set is very close to\W
but includes the dash as well, which is why it's spelled out here).to_slug 是一个很棒的 Rails 插件,可以处理几乎所有内容,包括时髦的字符,但它的实现非常简单。把它扔到字符串上,你就会被排序。这是浓缩的来源:
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:
我用过这个 gem。它很简单但很有用。
https://rubygems.org/gems/string_helpers
I've used this gem.It's simple but helpful.
https://rubygems.org/gems/string_helpers
我喜欢FriendlyId,它自称是创造鼻涕虫的“瑞士陆军推土机”。 https://github.com/norman/friend_id
I like FriendlyId, the self-professed "Swiss Army Bulldozer" of creating slugs. https://github.com/norman/friendly_id