Rails friendly_id删除用于URL生成的非ASCII字符

问题描述 投票:0回答:1

我想根据书名和作者自动生成子弹,可以是任何语言。在rails上使用friendly_id,并且当存在非ascii字符时,它将删除它们。我知道我可以通过如下方式对它们进行编码:

class Resource < ApplicationRecord
  extend FriendlyId
  friendly_id :title_and_author, use: :slugged

  def title_and_author
    "#{URI::encode(title)} by #{URI::encode(author)} #{language.language} book"
  end
end

这会产生不友好的长行d0-9b-d0-b5-d0-b4-d0-b8-20-d0-9c-d0-b0-d0-ba-d0-b1-d0-b5-d1-82-20-d0-9c-d1-86-d0-b5-d0-bd-d0-ba-d0-be-d0-b3-d0-be-20-d1-83-d0-b5-d0-b7-d0-b4-by-d0-9c-d0-b0-d1-82-spanish-book

我希望URL在本机脚本中包含单词,而不是编码版本中的单词。弹头如何包含俄文,日文,中文等?我也见过many posts suggesting including a translation gem,但必须更容易保存字符?为什么首先要删除字符?

ruby-on-rails friendly-id
1个回答
0
投票

默认情况下,FriendlyId使用Active Support的paramaterize弹头的方法。这种方法将智能地替换空间带破折号,以及带ASCII近似值的Unicode拉丁字符:

movie = Movie.create! :title => "Der Preis fürs Überleben"
movie.slug #=> "der-preis-furs-uberleben"

http://norman.github.io/friendly_id/file.Guide.html#Working_With_Slugs

您可以通过覆盖#normalize_friendly_id方法来覆盖段塞生成过程:

class User < ActiveRecord::Base
  friendly_id :name

  def normalize_friendly_id(string)
    string
  end
end

为什么要首先删除字符?

它称为音译,是出于兼容性原因而进行的。尽管现代的浏览器在url中支持UTF-8字符,但情况并非总是如此,服务器端的支持也参差不齐。

© www.soinside.com 2019 - 2024. All rights reserved.