Fixing as_json to always use a simple Hash and remove nils. History updates.

This commit is contained in:
Sam Lown 2011-05-19 00:08:58 +02:00
parent a284c65992
commit 1ef25c5015
3 changed files with 33 additions and 0 deletions

View file

@ -1,5 +1,15 @@
# CouchRest Model Change History # 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 ## 1.1.0.beta5 - 2011-04-30
* Major changes: * Major changes:

View file

@ -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?(:[]=)) 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 end
def as_json(options = nil)
Hash[self].reject{|k,v| v.nil?}.as_json(options)
end
# Returns the Class properties # Returns the Class properties
# #
# ==== Returns # ==== Returns

View file

@ -1,5 +1,6 @@
# encoding: utf-8 # encoding: utf-8
require File.expand_path('../../spec_helper', __FILE__) 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', 'cat')
require File.join(FIXTURE_PATH, 'more', 'person') require File.join(FIXTURE_PATH, 'more', 'person')
require File.join(FIXTURE_PATH, 'more', 'card') require File.join(FIXTURE_PATH, 'more', 'card')
@ -71,6 +72,24 @@ describe "Model properties" do
@card.updated_at.should_not be_nil @card.updated_at.should_not be_nil
end 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 describe '#read_attribute' do
it "should let you use read_attribute method" do it "should let you use read_attribute method" do
@card.last_name = "Aimonetti" @card.last_name = "Aimonetti"