conditional convert options paperclip

后端 未结 5 1443
[愿得一人]
[愿得一人] 2021-02-06 09:18

After some research I was able to add styles based on my image_class column.

Model.rb

has_attached_file :image,
                    


        
5条回答
  •  醉梦人生
    2021-02-06 10:10

    Add the convert_options into the styles themselves. Here is an example for a generic rails Image model which contains two styles and corresponding booleans to enable these styles.

    # == Schema Information
    #
    # Table name: images
    #
    #  id                 :integer          not null, primary key
    #  image_file_name    :string(255)
    #  image_content_type :string(255)
    #  image_file_size    :integer
    #  hero_style         :boolean 
    #  thumb_style        :boolean 
    #  image_updated_at   :datetime
    #  created_at         :datetime         not null
    #  updated_at         :datetime         not null
    #
    
    class Image < ActiveRecord::Base
    
      # These are the postprocessing options. 
      # The boolean _style? attributes controls which styles are created. 
    
      STYLES = {
        hero: {geometry: "2500x800#", convert_options: "-quality 75 -strip", source_file_options: ""},
        thumb: {geometry: "312x100#", convert_options: "-quality 75 -strip", source_file_options: ""}  
      }
    
      has_attached_file :image,
        styles: 
          lambda { |file|
            r = {}
            STYLES.keys.each do |stylename|
              r[stylename] = STYLES[stylename] if file.instance.method("%s_style?" % stylename).call
            end
            return r
          }
    
      validates_attachment :image, :presence => true,
      content_type: { content_type: ["image/jpeg", "image/png"] },
      file_name: {matches: [/png\Z/, /jpe?g\Z/]}
    
    
    
    end
    

提交回复
热议问题