diff --git a/lib/paperclip/has_attached_file.rb b/lib/paperclip/has_attached_file.rb index 1a79146b4..0e2215abe 100644 --- a/lib/paperclip/has_attached_file.rb +++ b/lib/paperclip/has_attached_file.rb @@ -12,7 +12,7 @@ def initialize(klass, name, options) def define define_flush_errors - define_getter + define_getters define_setter define_query register_new_attachment @@ -29,7 +29,12 @@ def define_flush_errors end end - def define_getter + def define_getters + define_instance_getter + define_class_getter + end + + def define_instance_getter name = @name options = @options @@ -50,9 +55,12 @@ def define_getter end end + def define_class_getter + @klass.extend(ClassMethods) + end + def define_setter name = @name - @klass.send :define_method, "#{@name}=" do |file| send(name).assign(file) end @@ -60,7 +68,6 @@ def define_setter def define_query name = @name - @klass.send :define_method, "#{@name}?" do send(name).file? end @@ -82,5 +89,11 @@ def add_paperclip_callbacks :define_paperclip_callbacks, :post_process, :"#{@name}_post_process") end + + module ClassMethods + def attachment_definitions + Paperclip::AttachmentRegistry.definitions_for(self.class) + end + end end end diff --git a/test/attachment_registry_test.rb b/test/attachment_registry_test.rb index cf26fccda..dc6c0193a 100644 --- a/test/attachment_registry_test.rb +++ b/test/attachment_registry_test.rb @@ -32,7 +32,7 @@ def setup should 'call the block with the class, attachment name, and options' do foo = Class.new expected_accumulations = [ - [foo,:avatar, { yo: 'greeting' }], + [foo, :avatar, { yo: 'greeting' }], [foo, :greeter, { ciao: 'greeting' }] ] expected_accumulations.each do |args| diff --git a/test/has_attached_file_test.rb b/test/has_attached_file_test.rb index ecd8397f3..6e452c2d8 100644 --- a/test/has_attached_file_test.rb +++ b/test/has_attached_file_test.rb @@ -15,6 +15,10 @@ class HasAttachedFileTest < Test::Unit::TestCase assert_adding_attachment('avatar').defines_method('avatar?') end + should 'define a method on the class to get all of its attachments' do + assert_adding_attachment('avatar').defines_class_method('attachment_definitions') + end + should 'flush errors as part of validations' do assert_adding_attachment('avatar').defines_validation end @@ -64,6 +68,17 @@ def defines_method(method_name) end end + def defines_class_method(method_name) + a_class = stub_class + a_class.class.stubs(:define_method) + + Paperclip::HasAttachedFile.define_on(a_class, @attachment_name, {}) + + assert_received(a_class, :extend) do |expect| + expect.with(Paperclip::HasAttachedFile::ClassMethods) + end + end + def defines_validation a_class = stub_class @@ -103,6 +118,7 @@ def stub_class before_destroy: nil, after_destroy: nil, define_paperclip_callbacks: nil, + extend: nil, name: 'Billy') end end