gpt4 book ai didi

ruby - rails omniauth 和 UTF-8 错误

转载 作者:数据小太阳 更新时间:2023-10-29 07:00:20 27 4
gpt4 key购买 nike

我最近在使用 omniauth 尝试填充 Google 登录的某些字段时遇到错误

Encoding::CompatibilityError: incompatible character encodings: ASCII-8BIT and UTF-8

"omniauth"=>
{"user_info"=>
{"name"=>"Joe McÙisnean",
"last_name"=>"McÙisnean",
"first_name"=>"Joe",
"email"=>"someemail@gmail.com"},
"uid"=>
"https://www.google.com/accounts/o8/id?id=AItOawnQmfdfsdfsdfdsfsdhGWmuLTiX2Id40k",
"provider"=>"google_apps"}

在我的用户模型中

  def apply_omniauth(omniauth)
#add some info about the user
self.email = omniauth['user_info']['email'] if email.blank?
self.name = omniauth['user_info']['name'] if name.blank?
self.name = omniauth['user_info'][:name] if name.blank?
self.nickname = omniauth['user_info']['nickname'] if nickname.blank?
self.nickname = name.gsub(' ','').downcase if nickname.blank?

unless omniauth['credentials'].blank?
user_tokens.build(:provider => omniauth['provider'],
:uid => omniauth['uid'],
:token => omniauth['credentials']['token'],
:secret => omniauth['credentials']['secret'])
else
user_tokens.build(:provider => omniauth['provider'], :uid => omniauth['uid'])
end
end

我对 UTF 编码不是很了解,所以我不确定应该在哪里指定编码?但我猜它在被放入用户模型并创建之前就已经存在了,我不确定该怎么做?

更新:

轨道 3.0.10全能认证 0.2.6 ruby 1.9.2PG 0.11.0

默认编码为UTF-8

这似乎不是它,所以我进一步挖掘并在 View 中发现了这个:

Showing /Users/holden/Code/someapp/app/views/users/registrations/_signup.html.erb where line #5 raised:

incompatible character encodings: ASCII-8BIT and UTF-8
Extracted source (around line #5):

2: <%= f.error_messages %>
3:
4: <%= f.input :name, :hint => 'your real name' %>
5: <%= f.input :nickname, :hint => 'Username of your choosing' %>
6:
7: <% unless @user.errors[:email].present? or @user.email %>
8: <%= f.input :email, :as => :hidden %>

更新更新:

它似乎是返回 ASCII-8BIT 字符的 omniauth gem,所以我的下一个问题是如何解析哈希并将其转换回 UTF8,这样我的应用程序就不会爆炸?

session[:omniauth] = omniauth.to_utf8

这个疯狂旅程的另一部分是当我将其输入控制台时

d={"user_info"=>{"email"=>"someemail@gmail.com", "first_name"=>"Joe", "last_name"=>"Mc\xC3\x99isnean", "name"=>"Joe Mc\xC3\x99isnean"}}

它会自动将其转换为 UTF-8,但在插入 session 时会爆炸

 => {"user_info"=>{"email"=>"someemail@gmail.com", "first_name"=>"Joe", "last_name"=>"McÙisnean", "name"=>"Joe McÙisnean"}} 

如果有的话,这将是一场痛苦的噩梦。

最佳答案

Omniauth 被证明是产生 ASCII-8BIT 的问题

我最终使用以下方法强制提交 Omniauth 哈希:

omniauth_controller.rb

session[:omniauth] = omniauth.to_utf8

添加递归方法强制将流氓 ASCII-8BIT 转换为 UTF8

some_initializer.rb

class Hash
def to_utf8
Hash[
self.collect do |k, v|
if (v.respond_to?(:to_utf8))
[ k, v.to_utf8 ]
elsif (v.respond_to?(:encoding))
[ k, v.dup.force_encode('UTF-8') ]
else
[ k, v ]
end
end
]
end
end

特别感谢tadman

recursively convert hash containing non-UTF chars to UTF

关于ruby - rails omniauth 和 UTF-8 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7349913/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com