解决Rails中的URI字符编码问题

时间:2010-08-13 06:31:09

标签: ruby-on-rails character-encoding uri

我正在使用Ruby on Rails应用程序,该应用程序对第​​三方服务进行客户端API调用。然后它从第三方API获取字符串并使用它们生成URI。

不幸的是,由于编码错误,Rails无法解析某些URI。我试过通过encodeURIComponent运行字符串,但这不能解决问题。

这是我得到的错误:

Processing ApplicationController#index (for 67.101.113.66 at 2010-08-12 23:24:55) [GET]
  Parameters: {"name"=>"Camilo Andr\xE9s \xD1ustes", "recipient_id"=>"279"}

ArgumentError (invalid byte sequence in US-ASCII):
  <internal:prelude>:8:in `synchronize'
  /home/heroku_rack/lib/static_assets.rb:9:in `call'
  /home/heroku_rack/lib/last_access.rb:25:in `call'
  /home/heroku_rack/lib/date_header.rb:14:in `call'
  thin (1.2.6) lib/thin/connection.rb:76:in `block in pre_process'
  thin (1.2.6) lib/thin/connection.rb:74:in `catch'
  thin (1.2.6) lib/thin/connection.rb:74:in `pre_process'
  thin (1.2.6) lib/thin/connection.rb:57:in `process'
  thin (1.2.6) lib/thin/connection.rb:42:in `receive_data'
  eventmachine (0.12.10) lib/eventmachine.rb:256:in `run_machine'
  eventmachine (0.12.10) lib/eventmachine.rb:256:in `run'
  thin (1.2.6) lib/thin/backends/base.rb:57:in `start'
  thin (1.2.6) lib/thin/server.rb:156:in `start'
  thin (1.2.6) lib/thin/controllers/controller.rb:80:in `start'
  thin (1.2.6) lib/thin/runner.rb:177:in `run_command'
  thin (1.2.6) lib/thin/runner.rb:143:in `run!'
  thin (1.2.6) bin/thin:6:in `<top (required)>'
  /usr/ruby1.9.1/bin/thin:19:in `load'

  /usr/ruby1.9.1/bin/thin:19:in `<main>'

如何正确处理这些字符串作为我的应用程序的输入?

1 个答案:

答案 0 :(得分:1)

这对我有用:<%= u name -%>

每次我必须在我的视图中传递身份验证令牌时使用此技术:  <%= u form_authenticity_token %>

由于以上是针对视图的,如果你想要特定于ruby:

require 'uri'
foo = "http://google.com?query=hello"

bad = URI.escape(foo)
good = URI.escape(foo, Regexp.new("[^#{URI::PATTERN::UNRESERVED}]"))

bad_uri = "http://mysite.com?service=#{bad}&bar=blah"
good_uri = "http://mysite.com?service=#{good}&bar=blah"

puts bad_uri
# outputs "http://mysite.com?service=http://google.com?query=hello&bar=blah"

puts good_uri
# outputs "http://mysite.com?service=http%3A%2F%2Fgoogle.com%3Fquery%3Dhello&bar=blah"

希望这有帮助。