How to send arguments to the Paperclip processor

I'm trying to figure out how to send the model value to the custom Paperclip processor, and just can't figure out why it is so complicated or what the solution may be, since I'm trying to solve it for a few days later ... Here is my code extracted from my model and processor.

From my model:

... 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] ... 

Why can't I use "self.id" to get the receipt id? How is it that "/:style/:id/:filename" translates into something like /original/1/abc.pdf , and if I put receipt_id: :id , all I get from options[:receipt_id] (see below) is :id instead of 1 ?

Do I need some kind of interpolation?

Processor code

 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 ... 
+4
source share
2 answers

I don’t know if this problem is a paper clip problem, but I can solve the problem with Ruby. Ruby allows you to call class methods in class definitions that provide intuitive DSLs, such as here:

 class MyModel < ActiveRecord::Base has_attached_file :receipt_file end 

The problem is that you expect to refer to the id model when calling this class method, but id is only available for class instances. So this will not work. Typically, such things are done using a block that evaluates at runtime as soon as an instance is available.

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

However, Paperclip needs to know how to accept and call a block, and I'm not sure what it does. Perhaps there is another way to achieve what you are trying to do, and I'm not sure what it is, but hopefully it helps.

+1
source

Add this to the initializer:

 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 

Then you could have a path like this:

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

Source: https://habr.com/ru/post/1432258/


All Articles