diff --git a/lib/dm-serializer/to_json.rb b/lib/dm-serializer/to_json.rb index febbde3..ca764ae 100644 --- a/lib/dm-serializer/to_json.rb +++ b/lib/dm-serializer/to_json.rb @@ -39,7 +39,12 @@ def as_json(options = {}) # TODO: This needs tests and also needs to be ported to #to_xml and # #to_yaml if options[:relationships] - options[:relationships].each do |relationship_name, opts| + # check for symbol or string argument, and splat-collect if we have one + rel = options[:relationships] + rel = *rel if (rel.kind_of?(Symbol) || rel.kind_of?(String)) + rel.each do |relationship_name, opts| + # opts will be null from splat, or with nested :relationships + opts ||= {} if respond_to?(relationship_name) result[relationship_name] = __send__(relationship_name).to_json(opts.merge(:to_json => false)) end diff --git a/spec/public/to_json_spec.rb b/spec/public/to_json_spec.rb index e3a8919..a610671 100644 --- a/spec/public/to_json_spec.rb +++ b/spec/public/to_json_spec.rb @@ -69,6 +69,17 @@ def deserialize(result) expect { Cow.new.as_json(nil) }.to_not raise_error end + it "handles nil for :relationships => options" do + # This is to prevent :relationships having to be called as: + # cow.to_json(:relationships => {:baby_cows => {}}) + expect { Cow.new.as_json(:relationships => [:baby_cows])}.to_not raise_error + end + + it "handles string and symbol arguments for :relationships" do + expect { Cow.new.as_json(:relationships => :baby_cows)}.to_not raise_error + expect { Cow.new.as_json(:relationships => 'baby_cows')}.to_not raise_error + end + it "serializes Discriminator types as strings" do Motorcycle.new.as_json[:type].should == "Motorcycle" end