是否可以直接将此文件保存到 ActiveStorage?
Is it possible to directly save this file to ActiveStorage?
我正在使用 ruby gem 进行 gpx 解析和编辑。我想将编辑后的结果存储在活动存储中。
gem有这个保存方法
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()
似乎是 export/save 数据的唯一途径,而 generate_xml_doc
是一种私有方法,有什么方法可以在不分叉 [=28 的情况下实现这一点=] 还是猴子修补它?
查看 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')
我正在使用 ruby gem 进行 gpx 解析和编辑。我想将编辑后的结果存储在活动存储中。
gem有这个保存方法
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()
似乎是 export/save 数据的唯一途径,而 generate_xml_doc
是一种私有方法,有什么方法可以在不分叉 [=28 的情况下实现这一点=] 还是猴子修补它?
查看 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')