MrRuru
MrRuru

Reputation: 1932

Paperclip : style aliases

Is there a way to define style aliases in paperclip (same transformations, same file path) ?

# 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'

I'm currently refactoring an application where there are a lot of duplicate styles. I would like to have it defined once, while not breaking the interface.

Upvotes: 1

Views: 408

Answers (2)

Eduardo Pacheco
Eduardo Pacheco

Reputation: 106

I made some changes to the apneadiving code to run in version ~ 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

Use it in the same way:

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

Upvotes: 0

apneadiving
apneadiving

Reputation: 115541

Here is a patch to add in an initializer:

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

Use it this way:

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

Upvotes: 3

Related Questions