【问题标题】:Paperclip : style aliases回形针:样式别名
【发布时间】:2012-08-31 12:57:45
【问题描述】:

有没有办法在回形针中定义样式别名(相同的转换,相同的文件路径)?

# in the model
has_attached_file :image, {
  :styles => {
    :thumb => "90x90>",
    :small => :thumb
  }
  [...]
}

# in the application
model.image.url(:thumb)
=> 'path/to/image/thumb.jpg'

model.image.url(:small)
=> 'path/to/image/thumb.jpg'

我目前正在重构一个有很多重复样式的应用程序。我希望它定义一次,而不破坏接口。

【问题讨论】:

  • 我会通过覆盖演示者中的方法来做到这一点
  • 稍后我会寻找更好的解决方案 :)
  • 相同。我想知道我是否错过了回形针文档中的配置字段,但似乎这不是受支持的功能。演示者似乎是最合乎逻辑的解决方案:)
  • 是的,但这会很麻烦:委托等...我们可以做得更好:)
  • 你用什么版本的回形针?

标签: ruby-on-rails paperclip


【解决方案1】:

这是一个要在初始化程序中添加的补丁:

module Paperclip
  Options.class_eval do
    attr_accessor :aliases

    def initialize_with_alias(attachment, hash)
      @aliases = hash[:aliases] || {}
      initialize_without_alias(attachment, hash)
    end

    alias_method_chain :initialize, :alias
  end

  Attachment.class_eval do
    def url_with_patch(style_name = default_style, use_timestamp = @options.use_timestamp)
      style_name = @options.aliases[style_name.to_sym] if @options.aliases[style_name.to_sym]
      url_without_patch(style_name, use_timestamp)
    end

    alias_method_chain :url, :patch
  end
end

这样使用:

has_attached_file :image, {
  :styles => {
    :thumb => "90x90>"
  }
  :aliases => { :small => :thumb }
}

【讨论】:

    【解决方案2】:

    我对@9​​87654321@ 代码进行了一些更改以在版本~ 4 中运行。

    module Paperclip
      Attachment.class_eval do
        def url_with_filter_aliases(style_name = default_style, options = {})
          style_name = find_alias(style_name) if find_alias(style_name).present?
          url_without_filter_aliases(style_name, options)
        end
    
        alias_method_chain :url, :filter_aliases
    
        private
    
        def find_alias(style_name)
          return if @options.blank?
    
          @options.dig(:aliases, style_name)
        end
      end
    end
    

    以同样的方式使用它:

    has_attached_file :image, {
      :styles => {
        :thumb => "90x90>"
      }
      :aliases => { :small => :thumb }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-24
      • 2015-06-13
      • 1970-01-01
      相关资源
      最近更新 更多