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.