Created
November 30, 2014 14:44
-
-
Save hamitturkukaya/1a52489bc83ab7227258 to your computer and use it in GitHub Desktop.
Conditional resize
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 Resizeable | |
def resize(hash) | |
key = hash.keys[0] | |
keys = hash[key].keys | |
arr = hash[key].values | |
val = {} | |
keys.each_with_index do |k, i| | |
val = val.merge(k => "#{arr[i][0]}x#{arr[i][1]}#") | |
end | |
return val unless self.send("#{key}?") | |
tempfile = self.send(key).queued_for_write[:original] | |
unless tempfile.nil? | |
geometry = Paperclip::Geometry.from_file(tempfile) | |
result = [] | |
ratio = geometry.width/ geometry.height | |
arr.each do |item| | |
min_width = item[0] | |
min_height = item[1] | |
if ratio > 1 | |
# Horizontal Image | |
result << horizontal(min_width, min_height, ratio) | |
else | |
# Vertical Image | |
result << vertical(min_width, min_height, ratio) | |
end | |
end | |
keys.each_with_index do |k, i| | |
val = val.merge(k => result[i]) | |
end | |
end | |
val | |
end | |
def horizontal(min_width, min_height, ratio) | |
final_height = min_height | |
final_width = final_height * ratio | |
if final_width > min_width | |
vertical(min_width, min_height, ratio) | |
else | |
"#{final_width.round}x#{final_height.round}!" | |
end | |
end | |
def vertical(min_width, min_height, ratio) | |
final_width = min_width | |
final_height = final_width / ratio | |
if final_height > min_height | |
horizontal(min_width, min_height, ratio) | |
else | |
"#{final_width.round}x#{final_height.round}!" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment