Paperclip attachments with dynamic style sizes from Model

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-18 13:35:40

问题


Using Rails 2, I try to separate different, dynamic image sizes trough another Model from the Paperclip-Model. My current approach, using a Proc, looks the following:

class File < ActiveRecord::Base
  has_many :sizes, :class_name => "FileSize"
  has_attached_file(
    :attachment,
    :styles => Proc.new { |instance| instance.attachment_sizes }
  )

  def attachment_sizes
    sizes = { :thumb => ["100x100"] }
    self.sizes.each do |size|
      sizes[:"#{size.id}"] = ["#{size.width}x#{size.height}"]
    end
    sizes
  end
end

class FileSize < ActiveRecord::Base
  belongs_to    :file

  after_create  :reprocess
  after_destroy :reprocess

  private

  def reprocess
    self.file.attachment.reprocess!
  end
end

Everything seems to work out fine but apparently no styles are processed and no image is being created.

Did anyone manage doing stuff like this?

-- Update --

Obviously the method attachment_sizes on instance sometimes is not defined for # - but shouldn't instance actually be #? For me this looks like altering instance..


回答1:


The solution is simple. instance in my first example Proc is an instance of Paperclip::Attachment. As I want to call a File method, one has to get the calling instance inside the Proc:

Proc.new { |clip| clip.instance.attachment_sizes }

instance represents File-instance in the given example.




回答2:


I'm assuming you have everything working with paperclip, such that you have uploaded an image and now the proc is just not working.

It should work. Try not putting the size in an array.

You are doing this

sizes = { :thumb => ["100x100"] }

But I have it where I'm not putting the size in an arry

sizes = { :thumb => "100x100" }

Give that a try :)



来源:https://stackoverflow.com/questions/4029480/paperclip-attachments-with-dynamic-style-sizes-from-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!