简体   繁体   中英

Rails and OpenURI

I'm trying to run the following snippet from a brand new rails project in the console:

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

This errors with:

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>'

I'm running on Rails 3.0.4 and Ruby 1.9.2. Any ideas on how to fix this? Thanks!

open() will accept both a string and a URI object.

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

The error you described will happen if open-uri is not included.

require 'open-uri'

open-uri想要一个字符串。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM