From 6df75a410c28f4248c54c905bd822ad31d551407 Mon Sep 17 00:00:00 2001 From: Timo Schilling Date: Sun, 28 Oct 2012 19:58:45 +0100 Subject: [PATCH] add Representable::JSON#collection_wrapper --- lib/representable/json.rb | 8 ++++++++ test/json_test.rb | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/lib/representable/json.rb b/lib/representable/json.rb index c8d54141..f3d505a6 100644 --- a/lib/representable/json.rb +++ b/lib/representable/json.rb @@ -21,6 +21,14 @@ module ClassMethods def from_json(*args, &block) create_represented(*args, &block).from_json(*args) end + + def collection_wrapper opions = {} + representer = self + Module.new do + include Representable::JSON::Collection + items({:extend => representer}.merge(opions)) + end + end end diff --git a/test/json_test.rb b/test/json_test.rb index e8748965..0b8f6dc9 100644 --- a/test/json_test.rb +++ b/test/json_test.rb @@ -485,6 +485,26 @@ module SongRepresenter end end + class CollectionRepresenterTest < MiniTest::Spec + describe "JSON#collection_wrapper" do + describe "with contained objects" do + before do + @song_representer = Module.new do + include Representable::JSON + property :name + end + end + + it "renders objects with #to_json" do + assert_json "[{\"name\":\"Days Go By\"},{\"name\":\"Can't Take Them All\"}]", [Song.new("Days Go By"), Song.new("Can't Take Them All")].extend(@song_representer.collection_wrapper).to_json + end + + it "returns objects array from #from_json" do + assert_equal [Song.new("Days Go By"), Song.new("Can't Take Them All")], [].extend(@song_representer.collection_wrapper(:class => Song)).from_json("[{\"name\":\"Days Go By\"},{\"name\":\"Can't Take Them All\"}]") + end + end + end + end require 'representable/json/hash' class HashRepresenterTest < MiniTest::Spec