How do I pass a variable watermark path to a paperclip watermark processor?

社会主义新天地 提交于 2019-12-05 10:20:29

You could use a proc for the styles:

  has_attached_file :image,
    :processors => [:watermark],
    :styles => proc { |attachment|
      {
        :thumbnail => ["80x80>"],
        :small => {
          :geometry => "200x200>",
          :watermark_path => attachment.instance.gallery.watermark.image.path(:small),
          :position => "Center"
        },
        :medium => {
          :geometry => "400x400>",
          :watermark_path => attachment.instance.gallery.watermark.image.path(:medium),
          :position => "Center"
        },
        :large => {
          :geometry => "600x600>",
          :watermark_path => attachment.instance.gallery.watermark.image.path(:large),
          :position => "Center"
        }
      }
    },
    [...]

But sometimes, the proc is called before the instance get all its attributes (so sometimes gallery may be nil because you may have assigned image before gallery_id).

The watermark_path needs to be a Pathname, try to use Rails.root.join like this:

has_attached_file :image,
:processors => [:watermark],
:styles => {
  :thumbnail => ["80x80>"],
  :small => {
    :geometry => "200x200>",
    :watermark_path => Rails.root.join("#{gallery.watermark.image.path(:small)}")
    :position => "Center"
  },
  :medium => {
    :geometry => "400x400>",
    :watermark_path => Rails.root.join("#{gallery.watermark.image.path(:medium)}")
    :position => "Center"
  },
  :large => {
    :geometry => "600x600>",
    :watermark_path => Rails.root.join("#{gallery.watermark.image.path(:large)}"),
    :position => "Center"
  }
}
[...]

I hope that helps you,

cheers.

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