3

我似乎无法让它工作。我想从不同的网络服务器中提取一个 CSV 文件以在我的应用程序中读取。这就是我想这样称呼它:

url = 'http://www.testing.com/test.csv'
records = FasterCSV.read(url, :headers => true, :header_converters => :symbol)

但这不起作用。我试过谷歌搜索,我想出的只是这段摘录:实用红宝石宝石

因此,我尝试将其修改如下:

require 'open-uri'
url = 'http://www.testing.com/test.csv'
csv_url = open(url)
records = FasterCSV.read(csv_url, :headers => true, :header_converters => :symbol)

...我收到一个can't convert Tempfile into String错误(来自 FasterCSV gem)。

谁能告诉我如何使这项工作?

4

5 回答 5

5
require 'open-uri'
url = 'http://www.testing.com/test.csv'
open(url) do |f|
  f.each_line do |line|
    FasterCSV.parse(line) do |row|
      # Your code here
    end
  end
end

http://www.ruby-doc.org/core/classes/OpenURI.html http://fastercsv.rubyforge.org/

于 2009-01-12T22:53:51.327 回答
1

我会用Net::HTTP例如检索文件并将其提供给FasterCSV

摘自ri Net::HTTP

 require 'net/http'
 require 'uri'

 url = URI.parse('http://www.example.com/index.html')
 res = Net::HTTP.start(url.host, url.port) {|http|
   http.get('/index.html')
 }
 puts res.body
于 2009-01-12T14:52:37.570 回答
1

你只是有一个小错字。您应该使用FasterCSV.parse而不是FasterCSV.read

data = open('http://www.testing.com/test.csv')
records = FasterCSV.parse(data)
于 2010-03-02T22:33:33.357 回答
0

我会用 rio 下载它 - 就像这样简单:

require 'rio'
require 'fastercsv'

array_of_arrays = FasterCSV.parse(rio('http://www.example.com/index.html').read)
于 2009-08-10T22:30:42.910 回答
0

我使用 Paperclip 上传 CSV 文件并将其保存到 Cloudfiles,然后使用 Delayed_job 开始文件处理。

这对我有用:

require 'open-uri'
url = 'http://www.testing.com/test.csv'
open(url) do |file|
  FasterCSV.parse(file.read) do |row|
    # Your code here
  end
end
于 2010-10-10T18:48:40.137 回答