Can I get available photo styles in Paperclip?
Asked Answered
R

1

5

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"
Redware answered 8/3, 2016 at 13:47 Comment(0)
C
9

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.

Charmainecharmane answered 8/3, 2016 at 14:12 Comment(1)
Thanks! Works perfect! I have decided to use Photo.new.photo.styles.keys, because styles defined in model OK for my code :)Chess

© 2022 - 2024 — McMap. All rights reserved.