【问题标题】:Is it possible to directly save this file to ActiveStorage?是否可以直接将此文件保存到 ActiveStorage?
【发布时间】:2019-03-19 01:00:09
【问题描述】:

我正在使用ruby gem 进行 gpx 解析和编辑。我想将编辑后的结果存储在活动存储中。

宝石有这种保存方法

    def write(filename, update_time = true)
      @time = Time.now if @time.nil? || update_time
      @name ||= File.basename(filename)
      doc = generate_xml_doc
      File.open(filename, 'w+') { |f| f.write(doc.to_xml) }
    end 

ActiveStorage 有一个保存的例子

@message.image.attach(io: File.open('/path/to/file'), filename: 'file.pdf')

我可以同时使用这两种方法,它应该可以工作,但是我将文件写入两次,并且文件系统上有一个额外的不需要的文件,需要稍后手动删除。

理想的情况是让 gpx gem 直接将数据传递给 ActiveStorage,让 AS 成为唯一保存文件的人。

鉴于write() 似乎是导出/保存数据的唯一方法,而generate_xml_doc 是一种私有方法,有没有什么方法可以在不分叉 gem 或猴子修补的情况下实现这一点?

【问题讨论】:

  • 您当然可以在其中一种或两种方法中使用Tempfile,这将有助于自动清理本地文件
  • 这是我的想法,但是 write 方法需要一个文件名字符串而不是对临时文件的引用,所以我不知道如何让 gem 写入临时文件。
  • 查看我刚刚发布的答案

标签: ruby-on-rails ruby rails-activestorage


【解决方案1】:

查看gem documentation,看起来您不需要使用write 方法,而是使用to_s 方法,该方法应该创建xml 字符串,然后您可以使用Tempfile 上传活动存储:

这是to_s 方法

def to_s(update_time = true)
  @time = Time.now if @time.nil? || update_time
  doc = generate_xml_doc
  doc.to_xml
end

#so assuming you have something like this:

bounds = GPX::Bounds.new(params)

file = Tempfile.new('foo')
file.path      # => A unique filename in the OS's temp directory,
               #    e.g.: "/tmp/foo.24722.0"
               #    This filename contains 'foo' in its basename.
file.write bounds.to_s
file.rewind    
@message.image.attach(io: file.read, filename: 'some_s3_file_name.xml') 
file.close
file.unlink    # deletes the temp file

更新(感谢@Matthew):

但您甚至可能不需要临时文件,这可能会起作用

bounds = GPX::Bounds.new(params)
@message.image.attach(io: StringIO.new(bounds.to_s),  name: 'some_s3_file_name.xml') 

【讨论】:

  • 根据 GPX bounds 的大小,我认为 Tempfile 可以完全避免使用 StringIO 否?
  • 我想你会想要@message.image.attach(io: StringIO.new(bounds.to_s), name: 'some_s3_file_name.xml')
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多