Rails에서 슬러그 (사람이 읽을 수있는 ID)를 생성하는 가장 좋은 방법
myblog.com/posts/donald-e-knuth 처럼요.
내가해야 내장이 작업을 수행 parameterize
하는 방법 ?
플러그인은 어떻습니까? 중복 슬러그 등을 처리하는 데 유용한 플러그인을 상상할 수 있습니다. 여기에 인기있는 Github 플러그인이 있습니다. 누구든지이 플러그인을 사용해 본 적이 있습니까?
기본적으로 슬러그는 완전히 해결 된 문제인 것처럼 보이며 바퀴를 재발 명하지 않습니다.
나는 다음을 사용합니다.
- 번역 &-> "and"및 @-> "at"
- 아포스트로피 대신 밑줄을 삽입하지 않으므로 "foo 's"-> "foos"
- 이중 밑줄을 포함하지 않음
- 밑줄로 시작하거나 끝나는 슬러그를 만들지 않습니다.
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
예를 들면 다음과 같습니다.
>> s = "mom & dad @home!"
=> "mom & dad @home!"
>> s.to_slug
> "mom_and_dad_at_home"
Rails에서는 #parameterize 를 사용할 수 있습니다 .
예를 들면 :
> "Foo bar`s".parameterize
=> "foo-bar-s"
슬러그를 생성하는 가장 좋은 방법은 Unidecode gem 을 사용하는 것 입니다. 그것은 지금까지 사용 가능한 가장 큰 음역 데이터베이스를 가지고 있습니다. 한자에 대한 음역도 있습니다. 모든 유럽 언어 (지역 방언 포함)를 다루는 것은 말할 것도 없습니다. 방탄 슬러그 생성을 보장합니다.
예를 들어 다음을 고려하십시오.
"Iñtërnâtiônàlizætiøn".to_slug
=> "internationalizaetion"
>> "中文測試".to_slug
=> "zhong-wen-ce-shi"
내 ruby_extensions 플러그인 의 String.to_slug 메서드 버전에서 사용합니다 . to_slug 메소드에 대해서는 ruby_extensions.rb 를 참조하십시오 .
내가 사용하는 것은 다음과 같습니다.
class User < ActiveRecord::Base
before_create :make_slug
private
def make_slug
self.slug = self.name.downcase.gsub(/[^a-z1-9]+/, '-').chomp('-')
end
end
꽤 자명하지만 이것의 유일한 문제는 이미 같은 것이 있다면 name-01이나 그와 비슷한 것이 아닐 것입니다.
예:
".downcase.gsub(/[^a-z1-9]+/, '-').chomp('-')".downcase.gsub(/[^a-z1-9]+/, '-').chomp('-')
출력 : -downcase-gsub-a-z1-9-chomp
누군가 관심이 있다면 밑줄 대신 대시를 만들도록 약간 수정했습니다.
def to_slug(param=self.slug)
# strip the string
ret = param.strip
#blow away apostrophes
ret.gsub! /['`]/, ""
# @ --> at, and & --> and
ret.gsub! /\s*@\s*/, " at "
ret.gsub! /\s*&\s*/, " and "
# replace all non alphanumeric, periods with dash
ret.gsub! /\s*[^A-Za-z0-9\.]\s*/, '-'
# replace underscore with dash
ret.gsub! /[-_]{2,}/, '-'
# convert double dashes to single
ret.gsub! /-+/, "-"
# strip off leading/trailing dash
ret.gsub! /\A[-\.]+|[-\.]+\z/, ""
ret
end
내 앱의 주요 문제는 아포스트로피였습니다. -s가 자체적으로 앉아있는 것을 거의 원하지 않습니다.
class String
def to_slug
self.gsub(/['`]/, "").parameterize
end
end
Unidecoder gem은 2007 년 이후로 업데이트되지 않았습니다.
Unidecoder gem의 기능을 포함하는 stringex gem을 추천합니다.
https://github.com/rsl/stringex
소스 코드를 보면 Unidecoder 소스 코드를 다시 패키징하고 새로운 기능을 추가하는 것 같습니다.
to_slug를 사용 합니다http://github.com/ludo/to_slug/tree/master
. 필요한 모든 작업을 수행합니다 ( '펑키 캐릭터'이스케이프). 도움이 되었기를 바랍니다.
편집 : 내 링크를 끊는 것 같습니다.
최근에 저도 같은 딜레마를 겪었습니다.
Since, like you, I don't want to reinvent the wheel, I chose friendly_id following the comparison on The Ruby Toolbox: Rails Permalinks & Slugs.
I based my decision on:
- number of github watchers
- no. of github forks
- when was the last commit made
- no. of downloads
Hope this helps in taking the decision.
I found the Unidecode gem to be much too heavyweight, loading nearly 200 YAML files, for what I needed. I knew iconv
had some support for the basic translations, and while it isn't perfect, it's built in and fairly lightweight. This is what I came up with:
require 'iconv' # unless you're in Rails or already have it loaded
def slugify(text)
text.downcase!
text = Iconv.conv('ASCII//TRANSLIT//IGNORE', 'UTF8', text)
# Replace whitespace characters with hyphens, avoiding duplication
text.gsub! /\s+/, '-'
# Remove anything that isn't alphanumeric or a hyphen
text.gsub! /[^a-z0-9-]+/, ''
# Chomp trailing hyphens
text.chomp '-'
end
Obviously you should probably add it as an instance method on any objects you'll be running it on, but for clarity, I didn't.
With Rails 3, I've created an initializer, slug.rb, in which I've put the following code:
class String
def to_slug
ActiveSupport::Inflector.transliterate(self.downcase).gsub(/[^a-zA-Z0-9]+/, '-').gsub(/-{2,}/, '-').gsub(/^-|-$/, '')
end
end
Then I use it anywhere I want in the code, it is defined for any string.
The transliterate transforms things like é,á,ô into e,a,o. As I am developing a site in portuguese, that matters.
I know this question has some time now. However I see some relatively new answers.
Saving the slug on the database is problematic, and you save redundant information that is already there. If you think about it, there is no reason for saving the slug. The slug should be logic, not data.
I wrote a post following this reasoning, and hope is of some help.
http://blog.ereslibre.es/?p=343
참고URL : https://stackoverflow.com/questions/1302022/best-way-to-generate-slugs-human-readable-ids-in-rails
'IT TIP' 카테고리의 다른 글
지도를 가질 수있는 좋은 방법이 있습니까? (0) | 2020.11.29 |
---|---|
list :: size () 정말 O (n)입니까? (0) | 2020.11.29 |
세미콜론이없고 IF / WHILE / FOR 문이없는 C의 hello world (0) | 2020.11.28 |
Git 클론-저장소를 찾을 수 없음 (0) | 2020.11.28 |
크롬 탭에서 X 버튼을 제거하는 방법이 있습니까? (0) | 2020.11.28 |