是否可以直接将此文件保存到 ActiveStorage? [英] Is it possible to directly save this file to ActiveStorage?

查看:54
本文介绍了是否可以直接将此文件保存到 ActiveStorage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using a ruby gem for gpx parsing and editing. I want to store the edited result in active storage.

宝石有这个保存方法

    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 有保存的例子

And ActiveStorage has an example for saving

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

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

I could use both of these and it should work but then I am writing the file twice as well as having a an extra unneeded file sitting on the filesystem that needs to be manually removed later.

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

The ideal situation would be to have the gpx gem directly pass the data to ActiveStorage and let AS be the only one saving the file.

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

Given write() seems to be the only way to export/save the data and generate_xml_doc is a private method, is there any way I can achieve this without forking the gem or monkey patching it?

推荐答案

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

Looking at the gem documentation, looks like you don't need to use the write method but instead use to_s method which should create the xml string which you can then use Tempfile to upload with active storage:

这是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):

UPDATED (thanks @Matthew):

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

But you may not even need the tempfile, this will probably work

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

这篇关于是否可以直接将此文件保存到 ActiveStorage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆