I have set up my models to use a polymorphic Image model. This is working fine, however I am wondering if it is possible to change the :styles setting for each model. Found some
I found the workaround to pickup styles on create.
The key is to implement before_post_process
and after_save
hooks.
class Image < ActiveRecord::Base
DEFAULT_STYLES = {
medium: "300x300>", thumb: "100x100>"
}
has_attached_file :file, styles: ->(file){ file.instance.styles }
validates_attachment_content_type :file, :content_type => /\Aimage\/.*\Z/
# Workaround to pickup styles from imageable model
# paperclip starts processing before all attributes are in the model
# so we start processing after saving
before_post_process ->{
!@file_reprocessed.nil?
}
after_save ->{
if !@file_reprocessed && (file_updated_at_changed? || imageable_type_changed?)
@file_reprocessed = true
file.reprocess!
end
}
belongs_to :imageable, polymorphic: true
def styles
if imageable_class.respond_to?(:image_styles)
imageable_class.image_styles
end || DEFAULT_STYLES
end
def imageable_class
imageable_type.constantize if imageable_type.present?
end
end
So you have to define image_styles class method in imageable_class In my case it was
class Property < ActiveRecord::Base
def self.image_styles
{
large: "570x380#",
thumb: "50x70#",
medium: "300x200#"
}
end
end