Ruby on rails 回形针处理器不更改文件内容
我正在尝试使用rails中的回形针处理器转换上传的文本文件附件的行。我可以使用调试器验证是否调用了我的处理器,但附加的文件是我的原始文件,而不是处理器编写的文件。这是我的处理器:Ruby on rails 回形针处理器不更改文件内容,ruby-on-rails,paperclip,Ruby On Rails,Paperclip,我正在尝试使用rails中的回形针处理器转换上传的文本文件附件的行。我可以使用调试器验证是否调用了我的处理器,但附加的文件是我的原始文件,而不是处理器编写的文件。这是我的处理器: module Paperclip class Utf8 < Processor def initialize(file, options={}, attachment=nil) super @file = file @attachment
module Paperclip
class Utf8 < Processor
def initialize(file, options={}, attachment=nil)
super
@file = file
@attachment = attachment
@current_format = File.extname(@file.path)
@format = options[:format]
@basename = File.basename(@file.path, @current_format)
end
def make
@file.rewind
tmp = Tempfile.new([@basename, @format])
IO.foreach(@file.path) do |line|
tmp << line.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
end
tmp.flush
tmp
end
end
end
模块回形针
Utf8类<处理器
def初始化(文件,选项={},附件=nil)
超级的
@file=file
@附件=附件
@当前_格式=File.extname(@File.path)
@格式=选项[:格式]
@basename=File.basename(@File.path,@current\u格式)
结束
def制造
@文件倒带
tmp=Tempfile.new([@basename,@format])
IO.foreach(@file.path)do|行|
tmp找到了一个解决方案:回形针将每个样式保存为一个单独的文件。要覆盖原始文件而不是创建新文件,我必须将模型更改为:
class List < ActiveRecord::Base
has_attached_file :file,
storage: :s3,
s3_credentials: Rails.root.join('config', 'aws.yml'),
bucket: Rails.application.config.s3_bucket,
processors: [:utf8],
styles: {
original: { # specifying original style here causes the original file to be overwritten
format: 'txt'
}
}
end
类列表
也许这不是您的情况,但曲别针通常会将原始文件名存储在数据库中,并根据您定义的转换,在文件系统上存储不同的版本。原始加上变换。因此,附件的内容在很大程度上取决于如何将其发送到浏览器。在你的情况下,你可能需要告诉你的控制器如何发送你的文件。啊,我现在明白了。每个处理器保存文件的新版本。如何让控制器发送不同的样式?
class List < ActiveRecord::Base
has_attached_file :file,
storage: :s3,
s3_credentials: Rails.root.join('config', 'aws.yml'),
bucket: Rails.application.config.s3_bucket,
processors: [:utf8],
styles: {
original: { # specifying original style here causes the original file to be overwritten
format: 'txt'
}
}
end