Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
895 views
in Technique[技术] by (71.8m points)

ruby on rails - Dynamic use of :default_url in Paperclip

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.

This is my first take:

EDIT to add full models:

class Service < ActiveRecord::Base

  attr_accessible :logo, :logo_file_name, :logo_content_type, :logo_file_size, :logo_updated_at

  belongs_to :category, :counter_cache => true

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

class Category < ActiveRecord::Base
  attr_accessible nil

  has_many :services
end

In my view, image_tag service.logo.url(:thumb) outputs:

undefined method `category' for #<Class:0x0000010a731620>

Any ideas?

EDIT2:

A working default_url is :default_url => "/logos/:style/missing.png",

SOLUTION:

See my own answer below.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...