Dynamic use of :default_url in Paperclip

前端 未结 4 1378
灰色年华
灰色年华 2020-12-16 17:31

I\'m trying to configure Paperclip to provide different missing images based on the instance\'s category attribute. Every category of the object has its own missing image.

4条回答
  •  时光说笑
    2020-12-16 18:09

    I found a solution, following this gist and this other question in stackoverflow.

    My working solution:

    Class Service
    
      has_attached_file :logo,
                :path => "/:id-:style-:filename",
                :url  => ":s3_eu_url",
                :default_url => :set_default_url_on_category,
                :styles => { :large => "600x400>",
                             :medium => "300x200>",
                             :small => "100x75>",
                             :thumb => "60x42>" }
    
      private
    
      def set_default_url_on_category
        "/logos/:style/#{category.name}.png"
      end
    end
    

    And an initializer paperclip_default_url_fix.rb

    module Paperclip
      module Interpolations
        def self.interpolate(pattern, *args)
          pattern = args.first.instance.send(pattern) if pattern.kind_of? Symbol
    
          all.reverse.inject(pattern.dup) do |result, tag|
            result.gsub(/:#{tag}/) do |match|
              send(tag, *args)
            end
          end
        end
      end
    end
    

提交回复
热议问题