可以直接将此文件保存到ActiveStorage吗?

时间:2018-10-14 12:13:09

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

我正在使用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或猴子修补它? / p>

1 个答案:

答案 0 :(得分: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') 
相关问题