如何将参数发送到Paperclip处理器

时间:2012-09-04 11:45:45

标签: ruby-on-rails ruby arguments paperclip processor

我正在尝试了解如何将模型值发送到Paperclip自定义处理器,并且无法弄清楚为什么它如此困难,或解决方案可能是什么,因为我正在尝试解决此问题几天了... 这是我的代码,从我的模型和处理器中提取。

从我的模特:

...
  has_attached_file :receipt_file,
                    :storage => :s3,
                    :s3_credentials => "#{Rails.root}/config/s3.yml",
                    :path => "/:style/:id/:filename",
                    :s3_protocol => "https",
                    :styles => { :text => { style: :original, receipt_id: self.id }},
                    processors: [:LearnProcessor]
...

为什么我不能使用“self.id”来获取收据ID? 如何将"/:style/:id/:filename"翻译成类似/original/1/abc.pdf的内容,如果我放receipt_id: :id,我从options[:receipt_id](见下文)获得的所有内容都是:id1

我需要某种插值吗?

处理器代码

module Paperclip

    class LearnProcessor < Processor
      attr_accessor :receipt_id,:style


      def initialize(file, options = {}, attachment = nil)
        @file           = file
        @current_format = File.extname(@file.path)
        @basename       = File.basename(@file.path, @current_format)
        @style = options[:style]
        @receipt_id = options[:receipt_id]
        puts "Options #{options.inspect}"
      end
...

2 个答案:

答案 0 :(得分:1)

我不知道这是否是特定于Paperclip的问题,但是我可以解决一个Ruby问题。 Ruby允许您在类定义中调用类方法,这些方法提供了类似这样的直观DSL:

class MyModel < ActiveRecord::Base
  has_attached_file :receipt_file
end

问题是,当您调用此类方法时,您希望引用模型的id,但id仅适用于类的实例。所以这不会奏效。通常,这种事情是使用在运行时评估的块来完成的,一旦实例可用。

has_attached_file :receipt_file,
                    # ...
                    :styles => { :text => { style: :original, receipt_id: lambda{self.id} }},

但是,Paperclip需要知道如何接受并调用该块,我不确定它是否存在。可能有一种不同的方式来实现你想要做的事情,我不确定那是什么,但希望这会有所帮助。

答案 1 :(得分:0)

在初始值设定项中添加:

module Paperclip
  module Interpolations
    def receipt_id attachment = nil, style_name = nil
      #you should handle the case when attachment and style_name are actually nil
      attachment.instance.receipt_id
    end
  end
end

然后你可以有一条路径:

:path => "/:style/:receipt_id/:filename",