From 1ef25c5015ad338cb53fdb4e73c9bb321097eafa Mon Sep 17 00:00:00 2001 From: Sam Lown Date: Thu, 19 May 2011 00:08:58 +0200 Subject: [PATCH] Fixing as_json to always use a simple Hash and remove nils. History updates. --- history.md | 10 ++++++++++ lib/couchrest/model/properties.rb | 4 ++++ spec/couchrest/property_spec.rb | 19 +++++++++++++++++++ 3 files changed, 33 insertions(+) diff --git a/history.md b/history.md index a6b7133..550f920 100644 --- a/history.md +++ b/history.md @@ -1,5 +1,15 @@ # CouchRest Model Change History +## 1.1.0 - 2011-05-XX + +* Minor fixes + * #as_json now correctly uses ActiveSupports methods. + * nil properties are now no longer sent in the document body. + * Rails 3.1 support (Peter Williams) + * Initialization blocks when creating new models (Peter Williams) + * Removed railties dependency (DAddYE) + + ## 1.1.0.beta5 - 2011-04-30 * Major changes: diff --git a/lib/couchrest/model/properties.rb b/lib/couchrest/model/properties.rb index 229c5bc..f421adf 100644 --- a/lib/couchrest/model/properties.rb +++ b/lib/couchrest/model/properties.rb @@ -12,6 +12,10 @@ module CouchRest raise "You can only mixin Properties in a class responding to [] and []=, if you tried to mixin CastedModel, make sure your class inherits from Hash or responds to the proper methods" unless (method_defined?(:[]) && method_defined?(:[]=)) end + def as_json(options = nil) + Hash[self].reject{|k,v| v.nil?}.as_json(options) + end + # Returns the Class properties # # ==== Returns diff --git a/spec/couchrest/property_spec.rb b/spec/couchrest/property_spec.rb index 6acc2f0..08ea325 100644 --- a/spec/couchrest/property_spec.rb +++ b/spec/couchrest/property_spec.rb @@ -1,5 +1,6 @@ # encoding: utf-8 require File.expand_path('../../spec_helper', __FILE__) +require File.join(FIXTURE_PATH, 'more', 'article') require File.join(FIXTURE_PATH, 'more', 'cat') require File.join(FIXTURE_PATH, 'more', 'person') require File.join(FIXTURE_PATH, 'more', 'card') @@ -71,6 +72,24 @@ describe "Model properties" do @card.updated_at.should_not be_nil end + describe "#as_json" do + + it "should provide a simple hash from model" do + @card.as_json.class.should eql(Hash) + end + + it "should remove properties from Hash if value is nil" do + @card.last_name = nil + @card.as_json.keys.include?('last_name').should be_false + end + + it "should pass options to Active Support's as_json" do + @card.last_name = "Aimonetti" + @card.as_json(:only => 'last_name').should eql('last_name' => 'Aimonetti') + end + + end + describe '#read_attribute' do it "should let you use read_attribute method" do @card.last_name = "Aimonetti"