Skip to content

Instantly share code, notes, and snippets.

@qrush
Created June 5, 2009 18:43
Show Gist options
  • Save qrush/124427 to your computer and use it in GitHub Desktop.
Save qrush/124427 to your computer and use it in GitHub Desktop.
From b7de7088f4888c9f552138f01e99f6a966884f64 Mon Sep 17 00:00:00 2001
From: Max Lapshin <max@maxidoors.ru>
Date: Wed, 4 Mar 2009 18:08:12 +0300
Subject: [PATCH] Added width, height and dir methods to attachment
---
lib/paperclip/attachment.rb | 17 +++++++++++++++++
test/attachment_test.rb | 14 ++++++++++++++
2 files changed, 31 insertions(+), 0 deletions(-)
diff --git a/lib/paperclip/attachment.rb b/lib/paperclip/attachment.rb
index 0913990..e55d063 100644
--- a/lib/paperclip/attachment.rb
+++ b/lib/paperclip/attachment.rb
@@ -121,6 +121,23 @@ module Paperclip
original_filename.nil? ? nil : interpolate(@path, style)
end
+ # calculates width using processor
+ def width(style = nil)
+ return 0 unless path(style)
+ Geometry.from_file(path(style)).width.to_i
+ end
+
+ # calculates height using processor
+ def height(style = nil)
+ return 0 unless path(style)
+ Geometry.from_file(path(style)).height.to_i
+ end
+
+ # tells, where attachment will be saved. Useful, if you want to after_destroy the whole directory of attachment
+ def dir
+ interpolate(@path.split("/")[0..-2].join("/"))
+ end
+
# Alias to +url+
def to_s style = nil
url(style)
diff --git a/test/attachment_test.rb b/test/attachment_test.rb
index d074747..1d71277 100644
--- a/test/attachment_test.rb
+++ b/test/attachment_test.rb
@@ -483,6 +483,10 @@ class AttachmentTest < Test::Unit::TestCase
assert_equal "/avatars/blah/missing.png", @attachment.url(:blah)
end
+ should "tell right dir, where file will be saved" do
+ assert_equal "./test/../tmp/avatars/dummies/original/#{@instance.id}", @attachment.dir
+ end
+
should "return nil as path when no file assigned" do
assert @attachment.to_file.nil?
assert_equal nil, @attachment.path
@@ -586,6 +590,16 @@ class AttachmentTest < Test::Unit::TestCase
assert_equal style[3].to_s, format.to_s
end
end
+
+ should "tell right sizes of saved files" do
+ [[:original, 434, 66, "PNG"],
+ [:large, 400, 61, "PNG"],
+ [:medium, 100, 15, "GIF"],
+ [:small, 32, 32, "JPEG"]].each do |style|
+ assert_equal style[1], @attachment.width(style[0])
+ assert_equal style[2], @attachment.height(style[0])
+ end
+ end
should "still have its #file attribute not be nil" do
assert ! (file = @attachment.to_file).nil?
--
1.5.4.3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment