Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get available photo styles in Paperclip?

I have some different styles(sizes), so I want to echo all of them near the text editor for user to choose one and use in the text.

To do this, I need to get all defined styles in model. How can I do this? (I need an automated way, because styles may change)

  # Photo
  has_attached_file :photo, :styles => { 
    :sthumb => "150x150>",
    :crop => "200x200#",
    :thumb => "300x300>",
    :small => "500x500>", 
    :large => "900x900>",
    :xlarge => "2600x2600>"
    }, 
  :default_url => "missing.png",
  :url => "/items/:id/:style.:basename.:extension"
like image 713
Gediminas Avatar asked Mar 08 '16 13:03

Gediminas


1 Answers

Instead of passing the styles definition directly to the has_attached_file method you can store them in a constant and use it too when showing the list of styles.

Something like this:

# Photo
DEFINED_STYLES = { 
  :sthumb => "150x150>",
  :crop => "200x200#",
  :thumb => "300x300>",
  :small => "500x500>", 
  :large => "900x900>",
  :xlarge => "2600x2600>"
}

has_attached_file :photo, :styles => DEFINED_STYLES, 
  :default_url => "missing.png",
  :url => "/items/:id/:style.:basename.:extension"

Then you can simply use the same constant elsewhere, e.g. in your view:

<%= Photo::DEFINED_STYLES.keys.map(&:to_s).join(", ") %>

Another option

Also, Paperclip styles can be grabbed from the model instance itself, without the need for defining constants, simply by:

Photo.new.photo.styles.keys
=> [:sthumb, :crop, :small, :large, :xlarge]

Where photo is the name of the Paperclip attachment used in has_attached_file.

like image 200
Matouš Borák Avatar answered Oct 19 '22 10:10

Matouš Borák