Commit 4793daab by Jon Yurek

Cache instance_read/_write. Make content_type validation work even with no _content_type field

parent b3770534
......@@ -258,6 +258,9 @@ module Paperclip
# match. Allows all by default.
# * +message+: The message to display when the uploaded file has an invalid
# content type.
# NOTE: If you do not specify an [attachment]_content_type field on your
# model, content_type validation will work _ONLY upon assignment_ and
# re-validation after the instance has been reloaded will always succeed.
def validates_attachment_content_type name, options = {}
attachment_definitions[name][:validations][:content_type] = lambda do |attachment, instance|
valid_types = [options[:content_type]].flatten
......@@ -265,7 +268,7 @@ module Paperclip
unless attachment.original_filename.blank?
unless valid_types.blank?
content_type = attachment.instance_read(:content_type)
unless valid_types.any?{|t| t === content_type }
unless valid_types.any?{|t| content_type.nil? || t === content_type }
options[:message] || "is not one of the allowed file types."
end
end
......
......@@ -243,6 +243,7 @@ module Paperclip
def instance_write(attr, value)
setter = :"#{name}_#{attr}="
responds = instance.respond_to?(setter)
self.instance_variable_set("@_#{setter.to_s.chop}", value)
instance.send(setter, value) if responds || attr.to_s == "file_name"
end
......@@ -251,6 +252,8 @@ module Paperclip
def instance_read(attr)
getter = :"#{name}_#{attr}"
responds = instance.respond_to?(getter)
cached = self.instance_variable_get("@_#{getter}")
return cached if cached
instance.send(getter) if responds || attr.to_s == "file_name"
end
......
......@@ -582,8 +582,16 @@ class AttachmentTest < Test::Unit::TestCase
assert_nothing_raised { @dummy.avatar = @file }
end
should "return nil when sent #avatar_updated_at" do
should "return the time when sent #avatar_updated_at" do
now = Time.now
Time.stubs(:now).returns(now)
@dummy.avatar = @file
assert now, @dummy.avatar.updated_at
end
should "return nil when reloaded and sent #avatar_updated_at" do
@dummy.save
@dummy.reload
assert_nil @dummy.avatar.updated_at
end
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment