Rails和OpenURI

时间:2011-02-18 20:22:11

标签: ruby-on-rails ruby

我正在尝试从控制台中的全新rails项目运行以下代码段:

uri = URI.parse("http://25.media.tumblr.com/avatar_279ec8ee3427_64.png")
data = open(uri)

此错误:

TypeError: can't convert URI::HTTP into String
    from (irb):24:in `open'
    from (irb):24
    from /Users/kevin/.rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.4/lib/rails/commands/console.rb:44:in `start'
    from /Users/kevin/.rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.4/lib/rails/commands/console.rb:8:in `start'
    from /Users/kevin/.rvm/gems/ruby-1.9.2-p136/gems/railties-3.0.4/lib/rails/commands.rb:23:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

我正在使用Rails 3.0.4和Ruby 1.9.2。有想法该怎么解决这个吗?谢谢!

2 个答案:

答案 0 :(得分:30)

open()将接受字符串和URI对象。

io = open("http://...")
io = open(URI.parse("http://..."))

如果未包含open-uri,则会出现您所描述的错误。

require 'open-uri'

答案 1 :(得分:9)

open-uri想要一个字符串。

data = open("http://25.media.tumblr.com/avatar_279ec8ee3427_64.png")