Rails 2.3.9查询参数的编码 [英] Rails 2.3.9 Encoding of Query Parameters
问题描述
如果我有类似于/ foo的内容吗?param =£
是否可以通过rails来将查询参数解码为utf8。
我尝试访问控制器中的参数,参数编码为ASCII-8BIT。这导致许多事情中断,因为我们很多其他的字符串被编码为UTF-8,而ruby不喜欢混合编码。
params [:param] .encoding == Encoding.find(ASCII-8BIT)
此解决方案摘自 http:// jasoncodes.com/posts/ruby19-rails2-encodings
感谢Jason对此的磨练!
如果您使用Rails 2.3.x系列,则需要创建一个名为config / initializers / utf8_params.rb的文件,其中包含以下内容以解决该问题。
raise检查这是否仍然需要+ Rails.version除非Rails.version =='2.3.10'
class ActionController :: Base
def force_utf8_params
traverse = lambda do | object,block |
if object.kind_of?(Hash)
object.each_value {| o | traverse.call(o,block)}
elsif object.kind_of?(Array)
object.each {| o | traverse.call(o,block)}
else
block.call(object)
end
object
end
force_encoding = lambda do | o |
o.force_encoding(Encoding :: UTF_8)if o.respond_to?(:force_encoding)
end
traverse.call(params,force_encoding)
end
before_filter: force_utf8_params
end
请务必查看文章中的其他提示特别是在视图中的魔法评论周围。再次感谢Jason。
Is it possible to get rails to decode query parameters to utf8.
If i have something like /foo?param=£
And I try to access the parameter in my controller the parameter is encoded as ASCII-8BIT. This causes lots of things to break because a lot of our other strings are encoded UTF-8 and ruby doesn't like mixing encodings.
params[:param].encoding == Encoding.find("ASCII-8BIT")
This solution is taken from the brilliant article at http://jasoncodes.com/posts/ruby19-rails2-encodings
Thanks a mill to Jason Weathered for this!
If you are on the Rails 2.3.x series, you need to create a file called config/initializers/utf8_params.rb with following content to fix the problem
raise "Check if this is still needed on " + Rails.version unless Rails.version == '2.3.10'
class ActionController::Base
def force_utf8_params
traverse = lambda do |object, block|
if object.kind_of?(Hash)
object.each_value { |o| traverse.call(o, block) }
elsif object.kind_of?(Array)
object.each { |o| traverse.call(o, block) }
else
block.call(object)
end
object
end
force_encoding = lambda do |o|
o.force_encoding(Encoding::UTF_8) if o.respond_to?(:force_encoding)
end
traverse.call(params, force_encoding)
end
before_filter :force_utf8_params
end
Be sure to check out the other tips in the article, especially around magic comments in views. Thanks again Jason.
这篇关于Rails 2.3.9查询参数的编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!