Commit 7a1dbd40 by Peter Vandenberk Committed by Prem Sichanugrist

the :default_url option for has_attached_file can now also be a Proc/lamba,…

the :default_url option for has_attached_file can now also be a Proc/lamba, which gets executed *before* it gets interpolated

Closes #253, Closes #360
parent 1d2e3bef
...@@ -123,7 +123,8 @@ module Paperclip ...@@ -123,7 +123,8 @@ module Paperclip
# security, however, for performance reasons. Set use_timestamp to false # security, however, for performance reasons. Set use_timestamp to false
# if you want to stop the attachment update time appended to the url # if you want to stop the attachment update time appended to the url
def url(style_name = default_style, use_timestamp = @use_timestamp) def url(style_name = default_style, use_timestamp = @use_timestamp)
url = original_filename.nil? ? interpolate(@default_url, style_name) : interpolate(@url, style_name) default_url = @default_url.is_a?(Proc) ? @default_url.call(self) : @default_url
url = original_filename.nil? ? interpolate(default_url, style_name) : interpolate(@url, style_name)
use_timestamp && updated_at ? [url, updated_at].compact.join(url.include?("?") ? "&" : "?") : url use_timestamp && updated_at ? [url, updated_at].compact.join(url.include?("?") ? "&" : "?") : url
end end
......
...@@ -14,6 +14,28 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -14,6 +14,28 @@ class AttachmentTest < Test::Unit::TestCase
assert_equal "#{Rails.root}/public/fake_models/1234/fake", @attachment.path assert_equal "#{Rails.root}/public/fake_models/1234/fake", @attachment.path
end end
should "return the url by interpolating the default_url option when no file assigned" do
@attachment = attachment :default_url => ":class/blegga.png"
@model = @attachment.instance
assert_nil @model.avatar_file_name
assert_equal "fake_models/blegga.png", @attachment.url
end
should "return the url by executing and interpolating the default_url Proc when no file assigned" do
@attachment = attachment :default_url => lambda { |a| ":class/blegga.png" }
@model = @attachment.instance
assert_nil @model.avatar_file_name
assert_equal "fake_models/blegga.png", @attachment.url
end
should "return the url by executing and interpolating the default_url Proc with attachment arg when no file assigned" do
@attachment = attachment :default_url => lambda { |a| a.instance.some_method_to_determine_default_url }
@model = @attachment.instance
@model.stubs(:some_method_to_determine_default_url).returns(":class/blegga.png")
assert_nil @model.avatar_file_name
assert_equal "fake_models/blegga.png", @attachment.url
end
context "Attachment default_options" do context "Attachment default_options" do
setup do setup do
rebuild_model rebuild_model
......
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