在 Paperclip 中动态使用 :default_url [英] Dynamic use of :default_url in Paperclip

查看:33
本文介绍了在 Paperclip 中动态使用 :default_url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试配置 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.

这是我第一次拍摄:

编辑以添加完整模型:

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

在我看来,image_tag service.logo.url(:thumb) 输出:

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

有什么想法吗?

编辑 2:

一个有效的 default_url 是 :default_url =>"/logos/:style/missing.png",

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

在下面查看我自己的答案.

See my own answer below.

推荐答案

我找到了一个解决方案,遵循 这个要点 和其他 问题堆栈溢出.

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

我的工作解决方案:

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

还有一个初始化 paperclip_default_url_fix.rb

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

这篇关于在 Paperclip 中动态使用 :default_url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆