Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Cache instance_read/_write. Make content_type validation work even wi…

…th no _content_type field
  • Loading branch information...
commit 4793daab83734dc019b1875642bdae01d14c01f9 1 parent b377053
@jyurek jyurek authored
View
5 lib/paperclip.rb
@@ -258,6 +258,9 @@ def validates_attachment_presence name, options = {}
# 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 @@ def validates_attachment_content_type name, options = {}
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
View
3  lib/paperclip/attachment.rb
@@ -243,6 +243,7 @@ def file?
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 @@ def instance_write(attr, value)
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
View
10 test/attachment_test.rb
@@ -582,8 +582,16 @@ def do_after_all; end
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
Please sign in to comment.
Something went wrong with that request. Please try again.