Commit 4ea2de63 by Ehren Kret Committed by Jon Yurek

Add +as_json+ method to Attachment class

The +as_json+ method enables Attachment objects to be rendered as JSON
by Rails' JSON rendering framework. The Attachment object is not a
native ActiveRecord attribute, but it can be accessed via the +:methods+
option provided to the +to_json+ method.
parent c65cbf35
...@@ -156,6 +156,10 @@ module Paperclip ...@@ -156,6 +156,10 @@ module Paperclip
url(style_name) url(style_name)
end end
def as_json(options = nil)
to_s((options && options[:style]) || default_style)
end
def default_style def default_style
@options[:default_style] @options[:default_style]
end end
......
...@@ -115,6 +115,17 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -115,6 +115,17 @@ class AttachmentTest < Test::Unit::TestCase
assert mock_url_generator_builder.has_generated_url_with_options?(:escape => true, :timestamp => true) assert mock_url_generator_builder.has_generated_url_with_options?(:escape => true, :timestamp => true)
end end
should "render JSON as default style" do
mock_url_generator_builder = MockUrlGeneratorBuilder.new
attachment = Paperclip::Attachment.new(:name,
:instance,
:default_style => 'default style',
:url_generator => mock_url_generator_builder)
attachment_json = attachment.as_json
assert mock_url_generator_builder.has_generated_url_with_style_name?('default style')
end
should "return the path based on the url by default" do should "return the path based on the url by default" do
@attachment = attachment :url => "/:class/:id/:basename" @attachment = attachment :url => "/:class/:id/:basename"
@model = @attachment.instance @model = @attachment.instance
...@@ -132,6 +143,24 @@ class AttachmentTest < Test::Unit::TestCase ...@@ -132,6 +143,24 @@ class AttachmentTest < Test::Unit::TestCase
assert_equal expected_path, avatar_attachment.path assert_equal expected_path, avatar_attachment.path
end end
should "render JSON as the URL to the attachment" do
avatar_attachment = attachment
model = avatar_attachment.instance
model.id = 1234
model.avatar_file_name = "fake.jpg"
assert_equal attachment.url, attachment.as_json
end
should "render JSON from the model when requested by :methods" do
rebuild_model
dummy = Dummy.new
dummy.id = 1234
dummy.avatar_file_name = "fake.jpg"
expected_string = '{"dummy":{"avatar":"/system/dummies/avatars/000/001/234/original/fake.jpg"}}'
# active_model pre-3.2 checks only by calling any? on it, thus it doesn't work if it is empty
assert_equal expected_string, dummy.to_json(:only => [:dummy_key_for_old_active_model], :methods => [:avatar])
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