-
-
Save maxschulze/721540 to your computer and use it in GitHub Desktop.
Save image size for paperclip photo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Photo < ActiveRecord::Base | |
has_attached_file :image, :styles => { :thumb => ['150x150#', :png], | |
:normal => ['660x660', :png] }, | |
:default_style => :normal | |
typed_serialize :sizes, Hash | |
before_save :cache_image_sizes | |
# Get size of this photo for specified style | |
# | |
# Returns a string of the schema "{Width}x{Height}" | |
def size(style = image.default_style) | |
style = style.to_sym | |
size = self.sizes[style] | |
end | |
private | |
def cache_image_sizes | |
self.image.styles.each do |style_name, style| | |
self.sizes[style_name] = Paperclip::Geometry.from_file( self.image.to_file(style_name) ).to_s | |
end | |
return true | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module PhotosHelper | |
def image_tag(source, options = {}) | |
unless source.is_a?(Photo) | |
super(source, options) | |
else | |
options = options.symbolize_keys | |
style = options.has_key?(:style) ? options.delete(:style).to_sym : source.image.default_style | |
super(source.image.url(style), {:size => source.size(style)}.merge(options)) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment