Skip to content

Commit

Permalink
as_json works on child object
Browse files Browse the repository at this point in the history
  • Loading branch information
bossmc committed Jul 3, 2012
1 parent 82096a5 commit a9d4378
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 2 deletions.
4 changes: 4 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,7 @@ group :test do
gem 'spork'
gem 'autotest'
end

group :development do
gem 'pry'
end
12 changes: 11 additions & 1 deletion lib/serializable_decorator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,17 @@ def instance_variable_get(name)
__getobj__.instance_variable_get(name) || super
end

def as_json
if __getobj__.respond_to?(:as_json) then
delegator_instance_vars = Delegator.instance_method(:instance_variables).bind(self).call
json_hash = Hash[delegator_instance_vars.map { | name | [name.to_s[1..-1], instance_variable_get(name) ] } ]
json_hash.merge!(__getobj__.as_json)
else
instance_values
end
end

def to_json
instance_values.to_json
as_json.to_json
end
end
2 changes: 1 addition & 1 deletion lib/serializable_decorator/version.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
module Delegators
module SerializableDecorator
VERSION = "0.0.2"
VERSION = "0.0.3"
end
end
16 changes: 16 additions & 0 deletions spec/serializable_decorator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,21 @@ class Test
attr_accessor :foo
end

class TestJson < Test
attr_accessor :quux
def as_json
{ extra: "baz", foo: @foo }
end
end

class TestDecorator < SerializableDecorator
attr_accessor :bar
end

describe SerializableDecorator do
before(:each) do
@td = TestDecorator.new(Test.new)
@tdj = TestDecorator.new(TestJson.new)
end

it "Original attributes are still available" do
Expand Down Expand Up @@ -75,4 +83,12 @@ class TestDecorator < SerializableDecorator
it "Should not include any extraneous entries in the JSON output" do
@td.to_json.should == "{}"
end

it "Should use the decorated object's as_json if it exists" do
@tdj.foo = 12
@tdj.bar = 13
@tdj.to_json.should include('"foo":12')
@tdj.to_json.should include('"bar":13')
@tdj.to_json.should include('"extra":"baz"')
end
end

0 comments on commit a9d4378

Please sign in to comment.