Created
June 5, 2009 18:59
-
-
Save qrush/124434 to your computer and use it in GitHub Desktop.
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
From e930a1fda7b3f2088203d56d06e85c87d8737f47 Mon Sep 17 00:00:00 2001 | |
From: Andrew Vit <andrew@avit.ca> | |
Date: Mon, 23 Feb 2009 01:03:53 -0800 | |
Subject: [PATCH] Added delegation for dedicated attachment models. | |
Useful for "has_many photos" situations where a | |
model is created just for holding the attachment. | |
--- | |
lib/paperclip.rb | 10 +++++++++- | |
test/attachment_test.rb | 14 ++++++++++++++ | |
2 files changed, 23 insertions(+), 1 deletions(-) | |
diff --git a/lib/paperclip.rb b/lib/paperclip.rb | |
index c62fa23..e0e1ee9 100644 | |
--- a/lib/paperclip.rb | |
+++ b/lib/paperclip.rb | |
@@ -194,7 +194,7 @@ module Paperclip | |
define_callbacks :before_post_process, :after_post_process | |
define_callbacks :"before_#{name}_post_process", :"after_#{name}_post_process" | |
- | |
+ | |
define_method name do |*args| | |
a = attachment_for(name) | |
(args.length > 0) ? a.to_s(args.first) : a | |
@@ -233,6 +233,14 @@ module Paperclip | |
end | |
end | |
+ # Makes attachment methods available directly on the model. Useful for | |
+ # models dedicated for holding an attachment, or when the model represents | |
+ # the attachment itself (e.g. in a has_many association). This avoids | |
+ # having to call +photo.attachment.url+ where +photo.url+ would be clearer. | |
+ def delegate_attachment_methods_for name | |
+ delegate :url, :path, :content_type, :original_filename, :size, :to => name | |
+ end | |
+ | |
# Adds errors if thumbnail creation fails. The same as specifying :whiny_thumbnails => true. | |
def validates_attachment_thumbnails name, options = {} | |
attachment_definitions[name][:whiny_thumbnails] = true | |
diff --git a/test/attachment_test.rb b/test/attachment_test.rb | |
index d074747..136c310 100644 | |
--- a/test/attachment_test.rb | |
+++ b/test/attachment_test.rb | |
@@ -266,6 +266,20 @@ class AttachmentTest < Test::Unit::TestCase | |
end | |
end | |
+ context "An attachment with delegated methods" do | |
+ setup do | |
+ Dummy.class_eval { delegate_attachment_methods_for :avatar } | |
+ @dummy = Dummy.new | |
+ @dummy.avatar = @file | |
+ end | |
+ | |
+ %w(url path content_type original_filename size).each do |method| | |
+ should "make .#{method} accessible on the model" do | |
+ assert_equal @dummy.avatar.send(method), @dummy.send(method) | |
+ end | |
+ end | |
+ end | |
+ | |
context "An attachment with :processors that is a proc" do | |
setup do | |
rebuild_model :styles => { :normal => '' }, :processors => lambda { |a| [ :test ] } | |
-- | |
1.6.1.2 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment