【问题标题】:Retrieve file from GridFS and pass as regular IO::File从 GridFS 检索文件并作为常规 IO::File 传递
【发布时间】:2012-07-23 04:44:52
【问题描述】:

我正在使用 GridFs 存储 Excel 文件等。我想使用电子表格 gem 来解析这些。

我已经尝试过了,但它(显然!)不起作用:

1.9.3p194 :036 > db = Mongo::Connection.new.db(Mongoid.database.name)
1.9.3p194 :037 > grid = Mongo::GridFileSystem.new(db)
1.9.3p194 :038 > f = grid.open('test1.xls', 'r')
 => #<GridIO _id: 500ef7cdc5ebb515c9000005>
1.9.3p194 :039 > Spreadsheet.open(f)
NoMethodError: undefined method `flush' for #<GridIO _id: 500ef7cdc5ebb515c9000005>

您有什么好的建议可以将 GridIO 类“转换”或“包装”成类似 IO::File 的实例,以便我可以将 Excel 文件传递​​给电子表格的打开方法。

电子表格打开方法采用 IO 实例或指定磁盘路径的字符串(后者在使用 GridFS 时无用):

(Object) open(io_or_path, mode = "rb+", &block)

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby mongodb gridfs


    【解决方案1】:

    看起来这是 ruby​​ 驱动程序的所需功能,但尚不存在。 https://jira.mongodb.org/browse/RUBY-368

    您可能会按照 jira 票证中的建议将一个块传递给 Spreadsheet.open:

    db = Mongo::Connection.new.db(Mongoid.database.name)
    Spreadsheet.open('filename', 'w') do |f|
       gridfs = Mongo::GridFileSystem.new(db)
       gridfs_file = gridfs.open('test1.xls', 'r')
       f.write(gridfs_file.read()) until gridfs_file.eof?
    end
    

    【讨论】:

    • 感谢您为我指明方向!我最终在该页面上获得了使用临时文件的建议。
    【解决方案2】:

    Emily 的指点很有帮助。暂时,最终使用了一个临时文件:

    Tempfile.open(["test", ".xls"]) do |fh|
     gridfs = Mongo::GridFileSystem.new(Mongoid.database)
     gridfs_file = gridfs.open('test1.xls', 'r')
     fh.binmode
     fh.write(gridfs_file.read)
     @xls = Excel.new(fh)
     fh.close
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-01
      • 2013-01-02
      • 2014-01-08
      • 2016-01-08
      • 2017-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多