rails omniauth和UTF
我使用omniauth尝试填充Google登录中的某些字段时出现了最近的错误
Encoding :: CompatibilityError:不兼容的字符编码:ASCII-8BIT和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编码知之甚少,所以我不确定我应该在哪里指定编码? 但是我猜在它进入用户模型并创建之前它已经到了,我不确定该怎么做?
更新:
Rails 3.0.10 Omniauth 0.2.6 Ruby 1.9.2 PG 0.11.0
默认编码是UTF-8
这似乎并不是这样,所以我进一步挖掘并发现了这个观点:
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 %>
更新更新:
它似乎是omniauth宝石是返回ASCII-8BIT字符,所以我的下一个问题是我如何解析散列并将其转换回UTF8,所以我的应用程序不会爆炸?
session[:omniauth] = omniauth.to_utf8
这种疯狂的骑行的另一个部分是当我把它输入控制台时
d={"user_info"=>{"email"=>"someemail@gmail.com", "first_name"=>"Joe", "last_name"=>"McxC3x99isnean", "name"=>"Joe McxC3x99isnean"}}
它会自动将其转换为UTF-8,但在推入会话时会爆炸
=> {"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
递归地将包含非UTF字符的散列转换为UTF
链接地址: http://www.djcxy.com/p/54753.html