开发者

Paperclip attachments with dynamic style sizes from Model

开发者 https://www.devze.com 2023-01-21 08:16 出处:网络
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:

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}"]
  开发者_JAVA技巧  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..


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.


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 :)

0

精彩评论

暂无评论...
验证码 换一张
取 消