Compare commits

...

86 commits

Author SHA1 Message Date
Sam Lown 819ddb7643 Merge pull request #132 from pezra/improve-auto-update-design-doc-flag-suppport
Improve auto update design doc flag suppport
2011-12-02 07:15:27 -08:00
Peter Williams 447b11a397 Improved auto_update_design_doc handling. 2011-12-01 09:19:15 -07:00
Peter Williams 88bb413ec2 Merge remote branch 'refs/remotes/canonical/master' into design-mapper-more-auto-update-design-doc-aware 2011-11-29 08:22:30 -07:00
Peter Williams 39c60d77d2 Used stored design document if auto_update_design_doc is disabled 2011-11-28 16:47:13 -07:00
Peter Williams f2c16144b0 #view method works when auto_update_design_doc is disabled 2011-11-16 15:30:46 -07:00
Marcos Tapajos 1c695f58bf update readme 2011-08-21 02:02:56 -03:00
Marcos Tapajos 2f00599209 added rake to gemfile 2011-08-21 01:59:48 -03:00
Marcos Tapajós 29de79290f Merge pull request #107 from Burgestrand/base-respond_to
Add CouchRest::Model::Base.respond_to_missing? and respond_to?
2011-08-20 21:58:11 -07:00
Marcos Tapajós 44e09f6083 Merge pull request #108 from Burgestrand/fix-specs
Tell contextual validations specs which database to use
2011-08-20 21:55:08 -07:00
Kim Burgestrand 465c0681e2 Tell contextual validations specs which database to use 2011-07-31 04:44:35 +02:00
Kim Burgestrand 72e3ac37d6 Add CouchRest::Model::Base.respond_to_missing? and respond_to? 2011-07-31 04:40:31 +02:00
Sam Lown 80e5ed2767 Updating histories and ensuring VERSION and date are good for 1.1.2 2011-07-23 17:38:49 +02:00
Sam Lown 3258ac22e9 updating to couchrest 1.1.2 and as_couch_json method 2011-07-19 21:28:44 +02:00
Sam Lown 3f1b2ea0c6 Casting array type properties now possible 2011-07-19 18:03:31 +02:00
Sam Lown 9d724aee47 Fix Embeddable and super issues. Prep for release 1.1.1 2011-07-04 18:53:25 +02:00
Sam Lown 8efa5208da Renaming casted model to embeddable and preparing for 1.1.0 launch@ 2011-06-25 19:24:43 +02:00
Sam Lown 05ed7b127f Merge branch 'master' of github.com:couchrest/couchrest_model 2011-06-25 17:36:41 +02:00
Sam Lown e40b96519e Preparing for 1.1.0 release 2011-06-25 17:36:32 +02:00
Sam Lown 4ba85b4cff Merge pull request #99 from crx/orm_fix
Set default ORM in Rails 3.1
2011-06-24 17:34:14 -07:00
Sam Lown e91812ca53 Comparing using attribute hash if ids are nil 2011-06-25 02:30:47 +02:00
Sam Lown a8a1372e57 Removing old fashioned class_evals (more to go) 2011-06-25 01:49:15 +02:00
Sam Lown 31b52ba012 Merge branch 'master' of github.com:couchrest/couchrest_model
Conflicts:
	lib/couchrest/model/base.rb
2011-06-25 01:02:19 +02:00
Sam Lown ca1d1cd51d Merge pull request #72 from lucasrenan/master
Adding a config generator
2011-06-24 15:59:41 -07:00
Sam Lown 406d2bc791 Casted Model now no longer depends on a Hash 2011-06-25 00:58:50 +02:00
Lucas Renan 9f7ce5d49b Merge branch 'master' of git://github.com/couchrest/couchrest_model 2011-06-21 14:03:04 -03:00
Sam Lown dca47ac3b2 Merge pull request #93 from crx/persisted_behavior
#persisted? should be false after a document has been destroyed
2011-06-17 17:14:57 -07:00
Chase DuBois b3a005b86d persisted? should be false after a document has been destroyed.
See https://github.com/rails/rails/blob/master/activemodel/CHANGELOG#L72
2011-06-12 14:27:45 -04:00
Chase DuBois f6d88530b7 set default ORM in Rails 3.1 2011-06-12 14:19:59 -04:00
Sam Lown 98772ae98a Updating history 2011-06-09 01:52:29 +02:00
Sam Lown 778e486328 Adding comparison using ids rather than hashes 2011-06-09 01:49:09 +02:00
Sam Lown 7875113d95 Merge branch 'master' of github.com:couchrest/couchrest_model
Conflicts:
	lib/couchrest/model/callbacks.rb
2011-06-09 01:10:13 +02:00
Sam Lown ca932df5ba Merge pull request #90 from kostia/validates_on
Should be able to set contextual validations
2011-06-08 16:06:04 -07:00
Sam Lown 3579e0e334 Refactoring tests and Validation callbacks 2011-06-09 01:05:22 +02:00
Kostiantyn Kahanskyi 1b5c431053 Should be able to set contextual validations
Contextual validations are active __only__ within
an appropriate context: either ”create" or ”update”.

validates(:name, :presence => true, :on => :create)

validates(:name, :presence => {:on => :update})

See http://edgeguides.rubyonrails.org/active_record_validations_callbacks.html#on

Should fix https://github.com/couchrest/couchrest_model/pull/90
2011-06-08 22:54:35 +02:00
Sam Lown ea4325f5bf Fixing assiging hashes to casted arrays properties 2011-06-08 19:14:01 +02:00
Sam Lown 7e054fd948 Merge branch 'master' of github.com:couchrest/couchrest_model
Conflicts:
	history.md
	lib/couchrest/model/property.rb
2011-06-08 18:37:00 +02:00
Sam Lown 7c7ee2c2b1 Upgrading to use CouchRest 1.1.0.pre3 and new Hash-less design 2011-06-08 18:22:35 +02:00
Marcos Tapajós d99150547c History update 2011-06-07 21:00:41 -03:00
Kostiantyn Kahanskyi 0bb00860d1 Casted array should notify changes on deletion
Otherwise there is no direct way to delete particular elements.

Workaround with assigning to another array without those elements
is pretty ugly.

* Should notify on deletion at a particular index (Array#delete_at)
* Should notify on deletion of a particular element (Array#delete)

Signed-off-by: Marcos Tapajós <tapajos@gmail.com>
2011-06-07 20:59:14 -03:00
Marcos Tapajós f244b51fbf Update History 2011-06-07 20:58:31 -03:00
Kostiantyn Kahanskyi d50d47c32a Should be able to assign a casted hash to a hash property
Fixes https://github.com/couchrest/couchrest_model/issues/68

Signed-off-by: Marcos Tapajós <tapajos@gmail.com>
2011-06-07 20:57:48 -03:00
Sam Lown a55cf56213 Merge pull request #88 from kostia/incl_docs_paginate
Should always include docs when paginating by Model##paginate
2011-06-06 04:19:44 -07:00
Kostiantyn Kahanskyi 5cee1734da Should always include docs when paginating by Model##paginate
Fixes https://github.com/couchrest/couchrest_model/issues/81
2011-06-06 12:51:02 +02:00
Sam Lown 6e025bb256 Updating history 2011-06-06 01:55:08 +02:00
Sam Lown f5be6c7679 Fixing problem with reloading models and dirty tracking 2011-06-06 01:53:36 +02:00
Sam Lown de1cab1271 Updating destroy specs for DocumentNotFound message 2011-06-05 11:26:50 +02:00
Sam Lown 634fdf8b2f Merge branch 'master' of github.com:couchrest/couchrest_model 2011-06-05 11:21:12 +02:00
Sam Lown 36157a01d3 Destroy method now freezes instead of removing ids 2011-06-05 11:21:01 +02:00
Sam Lown 84d7063608 Merge pull request #83 from pezra/init-blocks
Init blocks
2011-06-01 02:37:47 -07:00
Peter Williams 53bc7637e2 tests for #create and #create! init blocks 2011-05-31 16:31:37 -06:00
Peter Williams 9369ad96d3 Merge remote branch 'origin/master' into init-blocks 2011-05-31 16:03:21 -06:00
Peter Williams 2b9a5193b4 add init block support to #create and #create! 2011-05-31 16:03:08 -06:00
Marcos Tapajós 4e19fdfdda History update 2011-05-30 22:00:56 -03:00
Peter Williams 9b8564d9a8 Implement #get! and #find! class methods
Signed-off-by: Marcos Tapajós <tapajos@gmail.com>
2011-05-30 21:57:28 -03:00
Peter Williams f28cce1f0a Implement #get! and #find! class methods 2011-05-23 11:02:08 -06:00
Lucas Renan ccafde77ab Merge branch 'master' of git://github.com/couchrest/couchrest_model 2011-05-23 08:48:10 -03:00
Sam Lown fcd9e2ba8e Adding property build support to enable CastedArray#build 2011-05-21 14:16:39 +02:00
Sam Lown d56179aa6b Views for unique validations created on loading, not execution 2011-05-20 12:21:42 +02:00
Sam Lown 938bf2cf2c Fixing dirty tracking on collection_of association type 2011-05-20 02:15:18 +02:00
Lucas Renan a400d46333 Merge branch 'master' of git://github.com/couchrest/couchrest_model 2011-05-18 21:49:18 -03:00
Sam Lown fba1e53e20 Overriding couchrest's database delete method to ensure design cache is deleted 2011-05-19 00:37:17 +02:00
Sam Lown 9754f4633c Merge branch 'master' of github.com:couchrest/couchrest_model
Conflicts:
	lib/couchrest/model/properties.rb
2011-05-19 00:10:18 +02:00
Sam Lown 1ef25c5015 Fixing as_json to always use a simple Hash and remove nils. History updates. 2011-05-19 00:08:58 +02:00
Lucas Renan f11a99dbfb Merge branch 'master' of git://github.com/couchrest/couchrest_model 2011-05-17 22:27:00 -03:00
Sam Lown c5ae042c76 Merge pull request #74 from DAddYE/master
Remove railties dependency
2011-05-16 02:00:58 -07:00
Davide D'Agostino f8769400b6 Update Rakefile to use latest rspec. 2011-05-16 10:50:22 +02:00
Davide D'Agostino 14e96367a5 Remove dependency of railties, issue #69 2011-05-16 10:50:00 +02:00
Lucas Renan c3b7cc316d adding config generator 2011-05-15 14:41:13 -03:00
Sam Lown 3f7b1d38c1 Merge pull request #71 from pezra/init-blocks
Support providing an initialization block when creating new models
2011-05-11 23:12:59 -07:00
Peter Williams c9d2611bb7 Support providing an initialization block when creating new models 2011-05-11 13:53:28 -06:00
Sam Lown 1309fa7082 Merge pull request #70 from pezra/rails-3.1
Rails 3.1 support
2011-05-10 10:04:56 -07:00
Peter Williams 2669de9511 Use class_attribute rather than extlib_inheritable_attribute (which is removed in rails 3.1) 2011-05-09 09:47:27 -06:00
Peter Williams 2b0dc2b779 Removed unneeded require 2011-05-06 13:32:49 -07:00
Peter Williams 7f1f05cbca Dumped supported rails versions 2011-05-06 11:23:14 -07:00
Sam Lown a284c65992 Test fix 2011-04-30 13:20:09 +02:00
Sam Lown f3936bba1d Fixing history 2011-04-30 13:15:36 +02:00
Sam Lown e8e1722241 Changing model_type_key one last time to 'type'. General doc refinements for 1.1.0.beta5 release 2011-04-30 13:13:38 +02:00
Sam Lown da3e524020 Fixing issues with proxying and new database code 2011-04-30 01:04:04 +02:00
Sam Lown 814e38f75f Fixing issues when loading with rails 2011-04-30 00:34:12 +02:00
Sam Lown 85109b4b22 Finalizing support for automatic configuration 2011-04-29 23:06:31 +02:00
Sam Lown f3dd4ae06e Working on adding automated configuration support 2011-04-29 21:40:36 +02:00
Sam Lown 37c021a6b9 Started initial idea for automated database configuration 2011-04-29 17:24:11 +02:00
Sam Lown d62c2d1439 Adding filter support to design docs 2011-04-27 13:30:08 +02:00
Sam Lown 8025c5354f Ignore all gems 2011-04-27 13:11:15 +02:00
Sam Lown ce33cf1edd Docs updated 2011-04-21 17:29:13 +02:00
Sam Lown 18cd16acb8 Ugh, date 2011-04-20 16:47:47 +02:00
79 changed files with 1713 additions and 1161 deletions

1
.gitignore vendored
View file

@ -8,3 +8,4 @@ couchdb.std*
*.*~ *.*~
Gemfile.lock Gemfile.lock
spec.out spec.out
*.gem

589
README.md
View file

@ -3,6 +3,16 @@
CouchRest Models adds additional functionality to the standard CouchRest Document class such as CouchRest Models adds additional functionality to the standard CouchRest Document class such as
setting properties, callbacks, typecasting, and validations. setting properties, callbacks, typecasting, and validations.
## Documentation
Please visit the documentation project at [http://www.couchrest.info](http://www.couchrest.info). You're [contributions](https://github.com/couchrest/couchrest.github.com) to the documentation would be greatly appreciated!
General API: [http://rdoc.info/projects/couchrest/couchrest_model](http://rdoc.info/projects/couchrest/couchrest_model)
See the [update history](https://github.com/couchrest/couchrest_model/blob/master/history.md) for an up to date list of all the changes we've been working on recently.
## Notes
Originally called ExtendedDocument, the new Model structure uses ActiveModel, part of Rails 3, Originally called ExtendedDocument, the new Model structure uses ActiveModel, part of Rails 3,
for validations and callbacks. for validations and callbacks.
@ -11,13 +21,13 @@ it is not possible to load ActiveModel into programs that do not use ActiveSuppo
CouchRest Model is only properly tested on CouchDB version 1.0 or newer. CouchRest Model is only properly tested on CouchDB version 1.0 or newer.
*WARNING:* As of April 2011 and the release of version 1.1.0, the default model type key is 'model' instead of 'couchrest-type'. Simply updating your project will not work unless you migrate your data or set the configuration option in your initializers: *WARNING:* As of April 2011 and the release of version 1.1.0, the default model type key is 'type' instead of 'couchrest-type'. Simply updating your project will not work unless you migrate your data or set the configuration option in your initializers:
CouchRest::Model::Base.configure do |config| CouchRest::Model::Base.configure do |config|
config.model_type_key = 'couchrest-type' config.model_type_key = 'couchrest-type'
end end
This is because CouchRest Model's are not couchrest specific and may be used in any other system such as a Javascript library, the model type should reflect this. This is because CouchRest Model's are not couchrest specific and may be used in any other systems such as Javascript, the model type should reflect this. Also, we're all used to `type` being a reserved word in ActiveRecord.
## Install ## Install
@ -31,44 +41,43 @@ If you're using bundler, define a line similar to the following in your project'
gem 'couchrest_model' gem 'couchrest_model'
You might also consider using the latest git repository. We try to make sure the current version in git is stable and at the very least all tests should pass. ### Configuration
gem 'couchrest_model', :git => 'git://github.com/couchrest/couchrest_model.git' CouchRest Model is configured to work out the box with no configuration as long as your CouchDB instance is running on the default port (5984) on localhost. The default name of the database is either the name of your application as provided by the `Rails.application.class.to_s` call (with /application removed) or just 'couchrest' if none is available.
### Setup The library will try to detect a configuration file at `config/couchdb.yml` from the Rails root or `Dir.pwd`. Here you can configuration your database connection in a Rails-like way:
There is currently no standard way for telling CouchRest Model how it should access your database, this is something we're still working on. For the time being, the easiest way is to set a COUCHDB_DATABASE global variable to an instance of CouchRest Database, and call `use_database COUCHDB_DATABASE` in each model. development:
protocol: 'https'
host: sample.cloudant.com
port: 443
prefix: project
suffix: test
username: test
password: user
TODO: Add an example! Note that the name of the database is either just the prefix and suffix combined or the prefix plus any text you specifify using `use_database` method in your models with the suffix on the end.
### Development The example config above for example would use a database called "project_test". Heres an example using the `use_database` call:
CouchRest Model now comes with a Gemfile to help with development. If you want to make changes to the code, download a copy then run: class Project < CouchRest::Model::Base
use_database 'sample'
end
bundle install # The database object would be provided as:
Project.database #=> "https://test:user@sample.cloudant.com:443/project_sample_test"
That should set everything up for `rake spec` to be run correctly. Update the couchrest_model.gemspec if your alterations
use different gems.
## Generators ## Generators
### Configuration
$ rails generate couchrest_model:config
### Model ### Model
$ rails generate model person --orm=couchrest_model $ rails generate model person --orm=couchrest_model
## Useful links and extensions
Try some of these gems that add extra funcionality to couchrest_model:
* [memories](http://github.com/moonmaster9000/memories) - object versioning using attachments (Matt Parker)
* [couch_publish](http://github.com/moonmaster9000/couch_publish) - versioned state machine for draft and published documents (Matt Parker)
* [couch_photo](http://github.com/moonmaster9000/couch_photo) - attach images to documents with variations (Matt Parker)
* [copycouch](http://github.com/moonmaster9000/copycouch) - single document replication on documents (Matt Parker)
* [recloner](https://github.com/moonmaster9000/recloner) - clone documents easily (Matt Parker)
* [couchrest_localised_properties](https://github.com/samlown/couchrest_localised_properties) - Transparent support for localised properties (Sam Lown)
If you have an extension that you'd us to add to this list, please get in touch!
## General Usage ## General Usage
require 'couchrest_model' require 'couchrest_model'
@ -100,533 +109,22 @@ If you have an extension that you'd us to add to this list, please get in touch!
@cat.new? # false @cat.new? # false
@cat.random_text # Raises error! @cat.random_text # Raises error!
## Development
## Properties ### Preparations
A property is the definition of an attribute, it describes what the attribute is called, how it should CouchRest Model now comes with a Gemfile to help with development. If you want to make changes to the code, download a copy then run:
be type casted and other options such as the default value. These replace your typical
`add_column` methods found in relational database migrations.
Attributes with a property definition will have setter and getter methods defined for them. Any other attibute bundle install
can be set as if the model were a Hash, this funcionality is inherited from CouchRest Documents.
Here are a few examples of the way properties are used: That should set everything up for `rake spec` to be run correctly. Update the couchrest_model.gemspec if your alterations
use different gems.
class Cat < CouchRest::Model::Base ### Testing
property :name
property :birthday
end
@cat = Cat.new(:name => 'Felix', :birthday => 2.years.ago) The most complete documentation is the spec/ directory. To validate your CouchRest install, from the project root directory run `bundle install` to ensure all the development dependencies are available and then `rspec spec` or `bundle exec rspec spec`.
@cat.name # 'Felix'
@cat.birthday.is_a?(Time) # True!
@cat.save
@cat = Cat.find(@cat.id)
@cat.name # 'Felix'
@cat.birthday.is_a?(Time) # False!
Properties create getters and setters similar to the following:
def name
read_attribute('name')
end
def name=(value)
write_attribute('name', value)
end
Properties can also have a type which will be used for casting data retrieved from CouchDB when the attribute is set:
class Cat < CouchRest::Model::Base
property :name, String
property :last_fed_at, Time
end
@cat = Cat.new(:name => 'Felix', :last_fed_at => 10.minutes.ago)
@cat.last_fed_at.is_a?(Time) # True!
@cat.save
@cat = Cat.find(@cat.id)
@cat.last_fed_at < 20.minutes.ago # True!
Boolean or TrueClass types will create a getter with question mark at the end:
class Cat < CouchRest::Model::Base
property :awake, TrueClass, :default => true
end
@cat.awake? # true
Adding the `:default` option will ensure the attribute always has a value.
A read-only property will only have a getter method, and its value is set when the document
is read from the database. You can however update a read-only attribute using the `write_attribute` method:
class Cat < CouchRest::Model::Base
property :name, String
property :lives, Integer, :default => 9, :readonly => true
def fall_off_balcony!
write_attribute(:lives, lives - 1)
save
end
end
@cat = Cat.new(:name => "Felix")
@cat.fall_off_balcony!
@cat.lives # Now 8!
Mass assigning attributes is also possible in a similar fashion to ActiveRecord:
@cat.attributes = { :name => "Felix" }
@cat.save
Is the same as:
@cat.update_attributes(:name => "Felix")
By default, attributes without a property will not be updated via the `#attributes=` method. This provents useless data being passed to database, for example from an HTML form. However, if you would like truely
dynamic attributes, the `mass_assign_any_attribute` configuration option when set to true will
store everything you put into the `Base#attributes=` method.
## Property Arrays
An attribute may contain an array of data. CouchRest Model handles this, along
with casting, by defining the class of the child attributes inside an Array:
class Cat < CouchRest::Model::Base
property :name, String
property :nicknames, [String]
end
By default, the array will be ready to use from the moment the object as been instantiated:
@cat = Cat.new(:name => 'Fluffy')
@cat.nicknames << 'Buffy'
@cat.nicknames == ['Buffy']
When anything other than a string is set as the class of a property, the array will be converted
into special wrapper called a CastedArray. If the child objects respond to the `casted_by` method
(such as those created with CastedModel, below) it will contain a reference to the parent.
## Casted Models
CouchRest Model allows you to take full advantage of CouchDB's ability to store complex
documents and retrieve them using the CastedModel module. Simply include the module in
a Hash (or other model that responds to the [] and []= methods) and set any properties
you'd like to use. For example:
class CatToy < Hash
include CouchRest::Model::CastedModel
property :name, String
property :purchased, Date
end
class Cat < CouchRest::Model::Base
property :name, String
property :toys, [CatToy]
end
@cat = Cat.new(:name => 'Felix', :toys => [{:name => 'mouse', :purchased => 1.month.ago}])
@cat.toys.first.class == CatToy
@cat.toys.first.name == 'mouse'
Any hashes sent to the property will automatically be converted:
@cat.toys << {:name => 'catnip ball'}
@cat.toys.last.is_a?(CatToy) # True!
To use your own classes they *must* be defined before the parent uses them otherwise
Ruby will bring up a missing constant error. To avoid this, or if you have a really simple array of data
you'd like to model, CouchRest Model supports creating anonymous classes:
class Cat < CouchRest::Model::Base
property :name, String
property :toys do
property :name, String
property :rating, Integer
end
end
@cat = Cat.new(:name => 'Felix', :toys => [{:name => 'mouse', :rating => 3}, {:name => 'catnip ball', :rating => 5}])
@cat.toys.last.rating == 5
@cat.toys.last.name == 'catnip ball'
Anonymous classes will *only* create arrays of objects. If you're more of the traditional type, a block parameter
can be provided allowing you to use this variable before each method call inside the anonymous class. This is useful
if you need to access variables outside of the block.
## Views
CouchDB views can be quite difficult to get grips with at first as they are quite different from what you'd expect with SQL queries in a normal Relational Database. Checkout some of the [CouchDB documentation on views](http://wiki.apache.org/couchdb/Introduction_to_CouchDB_views) to get to grips with the basics. The key is to remember that CouchDB will only generate indexes from which you can extract consecutive rows of data, filtering other than between two points in a data set is not possible.
CouchRest Model has great support for views, and since version 1.1.0 we added support for a View objects that make accessing your data even easier.
### The Old Way
Here's an example of adding a view to our Cat class:
class Cat < CouchRest::Model::Base
property :name, String
property :toys, [CatToy]
view_by :name
end
The `view_by` method will create a view in the Cat's design document called "by_name". This will allow searches to be made for the Cat's name attribute. Calling `Cat.by_name` will send a query of to the database and return an array of all the Cat objects available. Internally, a map function is generated automatically and stored in CouchDB's design document for the current model, it'll look something like the following:
function(doc) {
if (doc['couchrest-type'] == 'Cat' && doc['name']) {
emit(doc.name, null);
}
}
By default, a special view called `all` is created and added to all couchrest models that allows you access to all the documents in the database that match the model. By default, these will be ordered by each documents id field.
It is also possible to create views of multiple keys, for example:
view_by :birthday, :name
This will create an view of all the cats' birthdays and their names called `by_birthday_and_name`.
Sometimes the automatically generate map function might not be sufficient for more complicated queries. To customize, add the :map and :reduce functions when creating the view:
view_by :tags,
:map =>
"function(doc) {
if (doc['model'] == 'Post' && doc.tags) {
doc.tags.forEach(function(tag){
emit(doc.tag, 1);
});
}
}",
:reduce =>
"function(keys, values, rereduce) {
return sum(values);
}"
Calling a view will return document objects by default, to get access to the raw CouchDB result add the `:raw => true` option to get a hash instead. Custom views can also be queried with `:reduce => true` to return reduce results. The default is to query with `:reduce => false`.
Views are generated (on a per-model basis) lazily on first-access. This means that if you are deploying changes to a view, the views for
that model won't be available until generation is complete. This can take some time with large databases. Strategies are in the works.
### View Objects
Since CouchRest Model 1.1.0 it is now possible to create views that return objects chainable objects, similar to those you'd find in the Sequel Ruby library or Rails 3's Arel. Heres an example of creating a few views:
class Post < CouchRest::Model::Base
property :title
property :body
property :posted_at, DateTime
property :tags, [String]
design do
view :by_title
view :by_posted_at_and_title
view :tag_list,
:map =>
"function(doc) {
if (doc['model'] == 'Post' && doc.tags) {
doc.tags.forEach(function(tag){
emit(doc.tag, 1);
});
}
}",
:reduce =>
"function(keys, values, rereduce) {
return sum(values);
}"
end
You'll see that this new syntax requires all views to be defined inside a design block. Unlike the old version, the keys to be used in a query are determined from the name of the view, not the other way round. Acessing data is the fun part:
# Prepare a query:
view = Post.by_posted_at_and_title.skip(5).limit(10)
# Fetch the results:
view.each do |post|
puts "Title: #{post.title}"
end
# Grab the CouchDB result information with the same object:
view.total_rows => 10
view.offset => 5
# Re-use and add new filters
filter = view.startkey([1.month.ago]).endkey([Date.current, {}])
# Fetch row results without the documents:
filter.rows.each do |row|
puts "Row value: #{row.value} Doc ID: #{row.id}"
end
# Lazily load documents (take last row from previous example):
row.doc => Fetch last Post document from database
# Using reduced queries is also easy:
tag_usage = Post.tag_list.reduce.group_level(1)
tag_usage.rows.each do |row|
puts "Tag: #{row.key} Uses: #{row.value}"
end
#### Pagination
The view objects have built in support for pagination based on the [kaminari](https://github.com/amatsuda/kaminari) gem. Methods are provided to match those required by the library to peform pagination.
For your view to support paginating the results, it must use a reduce function that provides a total count of the documents in the result set. By default, auto-generated views include a reduce function that supports this.
Use pagination as follows:
# Prepare a query:
@posts = Post.by_title.page(params[:page]).per(10)
# In your view, with the kaminari gem loaded:
paginate @posts
### Design Documents and Views
Views must be defined in a Design Document for CouchDB to be able to perform searches. Each model therefore must have its own Design Document. Deciding when to update the model's design doc is a difficult issue, as in production you don't want to be constantly checking for updates and in development maximum flexability is important. CouchRest Model solves this issue by providing the `auto_update_design_doc` configuration option and is true by default.
Each time a view or other design method is requested a quick GET for the design will be sent to ensure it is up to date with the latest changes. Results are cached in the current thread for the complete design document's URL, including the database, to try and limit requests. This should be fine for most projects, but dealing with multiple sub-databases may require a different strategy.
Setting the option to false will require a manual update of each model's design doc whenever you know a change has happened. This will be useful in cases when you do not want CouchRest Model to interfere with the views already store in the CouchRest database, or you'd like to deploy your own update strategy. Here's an example of a module that will update all submodules:
module CouchRestMigration
def self.update_design_docs
CouchRest::Model::Base.subclasses.each{|klass| klass.save_design_doc! if klass.respond_to?(:save_design_doc!)}
end
end
# Running this from your applications initializers would be a good idea,
# for example in Rail's application.rb or environments/production.rb:
config.after_initialize do
CouchRestMigration.update_design_docs
end
If you're dealing with multiple databases, using proxied models, or databases that are created on-the-fly, a more sophisticated approach might be required:
module CouchRestMigration
def self.update_all_design_docs
update_design_docs(COUCHREST_DATABASE)
Company.all.each do |company|
update_design_docs(company.proxy_database)
end
end
def self.update_design_docs(db)
CouchRest::Model::Base.subclasses.each{|klass| klass.save_design_doc!(db) if klass.respond_to?(:save_design_doc!}
end
end
# Command to run after a capistrano migration:
$ rails runner "CouchRestMigratin.update_all_design_docs"
## Assocations
Two types at the moment:
belongs_to :person
collection_of :tags
This is a somewhat controvesial feature of CouchRest Model that some document database purists may cringe at. CouchDB does not yet povide many features to support relationships between documents but the fact of that matter is that its a very useful paradigm for modelling data systems.
In the near future we hope to add support for a `has_many` relationship that takes of the _Linked Documents_ feature that arrived in CouchDB 0.11.
### Belongs To
Creates a property in the document with `_id` added to the end of the name of the foreign model with getter and setter methods to access the model.
Example:
class Cat < CouchRest::Model::Base
belongs_to :mother
property :name
end
kitty = Cat.new(:name => "Felix")
kitty.mother = Mother.find_by_name('Sophie')
Providing a object to the setter, `mother` in the example will automagically update the `mother_id` attribute. Retrieving the data later is just as expected:
kitty = Cat.find_by_name "Felix"
kitty.mother.name == 'Sophie'
Belongs_to accepts a few options to add a bit more felxibility:
* `:class_name` - the camel case string name of the class used to load the model.
* `:foreign_key` - the name of the property to use instead of the attribute name with `_id` on the end.
* `:proxy` - a string that when evaluated provides a proxy model that responds to `#get`.
The last option, `:proxy` is a feature currently in testing that allows objects to be loaded from a proxy class, such as `ClassProxy`. For example:
class Invoice < CouchRest::Model::Base
attr_accessor :company
belongs_to :project, :proxy => 'self.company.projects'
end
A project instance in this scenario would need to be loaded by calling `#get(project_id)` on `self.company.projects` in the scope of an instance of the Invoice. We hope to document and work on this powerful feature in the near future.
### Collection Of
A collection_of relationship is much like belongs_to except that rather than just one foreign key, an array of foreign keys can be stored. This is one of the great features of a document database. This relationship uses a proxy object to automatically update two arrays; one containing the objects being used, and a second with the foreign keys used to the find them.
The best example of this in use is with Labels:
class Invoice < CouchRest::Model::Base
collection_of :labels
end
invoice = Invoice.new
invoice.labels << Label.get('xyz')
invoice.labels << Label.get('abc')
invoice.labels.map{|l| l.name} # produces ['xyz', 'abc']
See the belongs_to relationship for the options that can be used. Note that this isn't especially efficient, a `get` is performed for each model in the array. As with a has_many relationship, we hope to be able to take advantage of the Linked Documents feature to avoid multiple requests.
## Validations
CouchRest Model automatically includes the new ActiveModel validations, so they should work just as the traditional Rails validations. For more details, please see the ActiveModel::Validations documentation.
CouchRest Model adds the possibility to check the uniqueness of attributes using the `validates_uniqueness_of` class method, for example:
class Person < CouchRest::Model::Base
property :title, String
validates_uniqueness_of :title
end
The uniqueness validation creates a new view for the attribute or uses one that already exists. You can
specify a different view using the `:view` option, useful for when the `unique_id` is specified and
you'd like to avoid the typical RestClient Conflict error:
unique_id :code
validates_uniqueness_of :code, :view => 'all'
Given that the uniqueness check performs a request to the database, it is also possible to include a `:proxy` parameter. This allows you to call a method on the document and provide an alternate proxy object.
Examples:
# Same as not including proxy:
validates_uniqueness_of :title, :proxy => 'class'
# Person#company.people provides a proxy object for people
validates_uniqueness_of :title, :proxy => 'company.people'
A really interesting use of `:proxy` and `:view` together could be where you'd like to ensure the ID is unique between several types of document. For example:
class Product < CouchRest::Model::Base
property :code
validates_uniqueness_of :code, :view => 'by_product_code'
view_by :product_code, :map => "
function(doc) {
if (doc['couchrest-type'] == 'Product' || doc['couchrest-type'] == 'Project') {
emit(doc['code']);
}
}
"
end
class Project < CouchRest::Model::Base
property :code
validates_uniqueness_of :code, :view => 'by_product_code', :proxy => 'Product'
end
Pretty cool!
## Proxy Support
CouchDB makes it really easy to create databases on the fly, so easy in fact that it is perfectly
feasable to have one database per user or per company or per whatever makes sense to split into
its own individual database. CouchRest Model now makes it really easy to support this scenario
using the proxy methods. Here's a quick example:
# Define a master company class, its children should be in their own DB
class Company < CouchRest::Model::Base
use_database COUCHDB_DATABASE
property :name
property :slug
proxy_for :invoices
def proxy_database
@proxy_database ||= COUCHDB_SERVER.database!("project_#{slug}")
end
end
# Invoices belong to a company
class Invoice < CouchRest::Model::Base
property :date
property :total
proxied_by :company
design do
view :by_date
end
end
By setting up our models like this, the invoices should be accessed via a company object:
company = Company.first
company.invoices.new # build a new invoice
company.invoices.by_date.first # find company's first invoice by date
Internally, all requests for invoices are passed through a model proxy. Aside from the
basic methods and views, it also ensures that some of the more complex queries are supported
such as validating for uniqueness and associations.
## Configuration
CouchRest Model supports a few configuration options. These can be set either for the whole Model code
base or for a specific model of your chosing. To configure globally, provide something similar to the
following in your projects initializers or environments:
CouchRest::Model::Base.configure do |config|
config.mass_assign_any_attribute = true
config.model_type_key = 'couchrest-type'
end
To set for a specific model:
class Cat < CouchRest::Model::Base
mass_assign_any_attribute true
end
Options currently avilable are:
* `mass_assign_any_attribute` - false by default, when true any attribute may be updated via the update_attributes or attributes= methods.
* `model_type_key` - 'model' by default, is the name of property that holds the class name of each CouchRest Model.
* `auto_update_design_doc` - true by default, every time a view is requested and this option is true, a quick check will be performed to ensure the model's design document is up to date. When disabled, you're design documents will never be updated automatically and you'll need to perform updates manually. Results are cached on a per-database and per-design basis to help lower the number of requests. See the View section for more details.
## Notable Issues
None at the moment...
## Testing
The most complete documentation is the spec/ directory. To validate your CouchRest install, from the project root directory run `rake`, or `autotest` (requires RSpec and optionally ZenTest for autotest support).
## Docs
API: [http://rdoc.info/projects/couchrest/couchrest_model](http://rdoc.info/projects/couchrest/couchrest_model)
Check the wiki for documentation and examples [http://wiki.github.com/couchrest/couchrest_model](http://wiki.github.com/couchrest/couchrest_model)
We will not accept pull requests to the project without sufficient tests.
## Contact ## Contact
@ -636,3 +134,4 @@ Follow us on Twitter: [http://twitter.com/couchrest](http://twitter.com/couchres
Also, check [http://twitter.com/#search?q=%23couchrest](http://twitter.com/#search?q=%23couchrest) Also, check [http://twitter.com/#search?q=%23couchrest](http://twitter.com/#search?q=%23couchrest)

View file

@ -1,21 +1,18 @@
require 'rubygems' require 'rubygems'
require 'bundler' require 'bundler'
Bundler::GemHelper.install_tasks require 'rspec/core/rake_task'
require 'rake'
require "rake/rdoctask" require "rake/rdoctask"
require 'rspec' Bundler::GemHelper.install_tasks
require 'rspec/core/rake_task'
desc "Run all specs" desc "Run all specs"
Rspec::Core::RakeTask.new(:spec) do |spec| RSpec::Core::RakeTask.new(:spec) do |spec|
spec.rspec_opts = ["--color"] spec.rspec_opts = ["--color"]
spec.pattern = 'spec/**/*_spec.rb' spec.pattern = 'spec/**/*_spec.rb'
end end
desc "Print specdocs" desc "Print specdocs"
Rspec::Core::RakeTask.new(:doc) do |spec| RSpec::Core::RakeTask.new(:doc) do |spec|
spec.rspec_opts = ["--format", "specdoc"] spec.rspec_opts = ["--format", "specdoc"]
spec.pattern = 'spec/*_spec.rb' spec.pattern = 'spec/*_spec.rb'
end end

View file

@ -1 +1 @@
1.1.0.beta4 1.1.2

View file

@ -6,7 +6,7 @@ Gem::Specification.new do |s|
s.required_rubygems_version = Gem::Requirement.new("> 1.3.1") if s.respond_to? :required_rubygems_version= s.required_rubygems_version = Gem::Requirement.new("> 1.3.1") if s.respond_to? :required_rubygems_version=
s.authors = ["J. Chris Anderson", "Matt Aimonetti", "Marcos Tapajos", "Will Leinweber", "Sam Lown"] s.authors = ["J. Chris Anderson", "Matt Aimonetti", "Marcos Tapajos", "Will Leinweber", "Sam Lown"]
s.date = %q{2011-01-16} s.date = File.mtime('VERSION')
s.description = %q{CouchRest Model provides aditional features to the standard CouchRest Document class such as properties, view designs, associations, callbacks, typecasting and validations.} s.description = %q{CouchRest Model provides aditional features to the standard CouchRest Document class such as properties, view designs, associations, callbacks, typecasting and validations.}
s.email = %q{jchris@apache.org} s.email = %q{jchris@apache.org}
s.extra_rdoc_files = [ s.extra_rdoc_files = [
@ -23,13 +23,14 @@ Gem::Specification.new do |s|
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) } s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.require_paths = ["lib"] s.require_paths = ["lib"]
s.add_dependency(%q<couchrest>, "1.1.0.pre2") s.add_dependency(%q<couchrest>, "~> 1.1.2")
s.add_dependency(%q<mime-types>, "~> 1.15") s.add_dependency(%q<mime-types>, "~> 1.15")
s.add_dependency(%q<activemodel>, "~> 3.0.5") s.add_dependency(%q<activemodel>, "~> 3.0")
s.add_dependency(%q<tzinfo>, "~> 0.3.22") s.add_dependency(%q<tzinfo>, "~> 0.3.22")
s.add_dependency(%q<railties>, "~> 3.0.0") s.add_development_dependency(%q<rspec>, "~> 2.6.0")
s.add_development_dependency(%q<rspec>, ">= 2.0.0") s.add_development_dependency(%q<json>, ["~> 1.5.1"])
s.add_development_dependency(%q<rack-test>, ">= 0.5.7") s.add_development_dependency(%q<rack-test>, ">= 0.5.7")
s.add_development_dependency("rake", ">= 0.8.0")
# s.add_development_dependency("jruby-openssl", ">= 0.7.3") # s.add_development_dependency("jruby-openssl", ">= 0.7.3")
end end

View file

@ -1,4 +1,67 @@
== 1.1.0.beta4 # CouchRest Model Change History
## 1.1.3
* CouchRest::Model::Base.respond_to_missing? and respond_to? (Kim Burgestrand)
## 1.1.2 - 2011-07-23
* Minor fixes
* Upgrade to couchrest 1.1.2
* Override as_couch_json to ensure nil values not stored
* Removing restriction that prohibited objects that cast as an array to be loaded.
## 1.1.1 - 2011-07-04
* Minor fix
* Bumping CouchRest version dependency for important initialize method fix.
* Ensuring super on Embeddable#initialize can be called.
## 1.1.0 - 2011-06-25
* Major Alterations
* CastedModel no longer requires a Hash. Automatically includes all required methods.
* CastedModel module renamed to Embeddable (old still works!)
* Minor Fixes
* Validation callbacks now support context (thanks kostia)
* Document comparisons now performed using database and document ID (pointer by neocsr)
* Automatic config generation now supported (thanks lucasrenan)
* Comparing documents resorts to Hash comparison if both IDs are nil. (pointer by kostia)
## 1.1.0.rc1 - 2011-06-08
* New Features
* Properties with a nil value are now no longer sent to the database.
* Now possible to build new objects via CastedArray#build
* Implement #get! and #find! class methods
* Now is possible delete particular elements in casted array(Kostiantyn Kahanskyi)
* Minor fixes
* #as_json now correctly uses ActiveSupports methods.
* Rails 3.1 support (Peter Williams)
* Initialization blocks when creating new models (Peter Williams)
* Removed railties dependency (DAddYE)
* DesignDoc cache refreshed if a database is deleted.
* Fixing dirty tracking on collection_of association.
* Uniqueness Validation views created on initialization, not on demand!
* #destroy freezes object instead of removing _id and _rev, better for callbacks (pointer by karmi)
* #destroyed? method now available
* #reload no longer uses Hash#merge! which was causing issues with dirty tracking on casted models. (pointer by kostia)
* Non-property mass assignment on #new no longer possible without :directly_set_attributes option.
* Using CouchRest 1.1.0.pre3. (No more Hashes!)
* Fixing problem assigning a CastedHash to a property declared as a Hash (Kostiantyn Kahanskyi, gfmtim)
## 1.1.0.beta5 - 2011-04-30
* Major changes:
* Database auto configuration, with connection options!
* Changed default CouchRest Model type to 'type' to be more consistent with ActiveRecord's reserverd words we're all used to (sorry for the change again!!)
* Minor changes
* Added filter option to designs (Used with CouchDB _changes feeds)
## 1.1.0.beta4
* Major changes: * Major changes:
* Fast Dirty Tracking! Many thanks to @sobakasu (Andrew Williams) * Fast Dirty Tracking! Many thanks to @sobakasu (Andrew Williams)
@ -10,11 +73,11 @@
* Added "auto_update_design_doc" configuration option. * Added "auto_update_design_doc" configuration option.
* Using #descending on View object will automatically swap startkey with endkey. * Using #descending on View object will automatically swap startkey with endkey.
== 1.1.0.beta3 ## 1.1.0.beta3
* Removed * Removed
== 1.1.0.beta2 ## 1.1.0.beta2
* Minor enhancements: * Minor enhancements:
* Time handling improved in accordance with CouchRest 1.1.0. Always set to UTC. * Time handling improved in accordance with CouchRest 1.1.0. Always set to UTC.
@ -23,7 +86,7 @@
* Unique Validation now supports scopes! * Unique Validation now supports scopes!
* Added support for #keys with list on Design View. * Added support for #keys with list on Design View.
== 1.1.0.beta ## 1.1.0.beta
* Epic enhancements: * Epic enhancements:
* Added "View" object for dynamic view queries * Added "View" object for dynamic view queries
@ -37,7 +100,7 @@
* Numeric types can be casted from strings with leading or trailing whitespace (thanks chrisdurtschi) * Numeric types can be casted from strings with leading or trailing whitespace (thanks chrisdurtschi)
* CollectionProxy no longer provided by default with simple views (pending deprication) * CollectionProxy no longer provided by default with simple views (pending deprication)
== CouchRest Model 1.0.0 ## CouchRest Model 1.0.0
* Major enhancements * Major enhancements
* Support for configuration module and "model_type_key" option for overriding model's type key * Support for configuration module and "model_type_key" option for overriding model's type key
@ -56,7 +119,7 @@ Notes:
Until these have been resolved (if possible?!) they should not be included. See the Until these have been resolved (if possible?!) they should not be included. See the
'active_model_attrs' if you'd like to test. 'active_model_attrs' if you'd like to test.
== CouchRest Model 1.0.0.beta8 ## CouchRest Model 1.0.0.beta8
* Major enhancements * Major enhancements
* Added model generator * Added model generator
@ -67,7 +130,7 @@ Notes:
* Parsing times without zone * Parsing times without zone
* Using latest rspec (2.0.0.beta.19) * Using latest rspec (2.0.0.beta.19)
== CouchRest Model 1.0.0.beta7 ## CouchRest Model 1.0.0.beta7
* Major enhancements * Major enhancements
* Renamed ExtendedDocument to CouchRest::Model * Renamed ExtendedDocument to CouchRest::Model
@ -83,7 +146,7 @@ Notes:
* Removed support for auto_validate! and :length on properties * Removed support for auto_validate! and :length on properties
== 1.0.0.beta6 ## 1.0.0.beta6
* Major enhancements * Major enhancements
* Added support for anonymous CastedModels defined in Documents * Added support for anonymous CastedModels defined in Documents
@ -97,12 +160,12 @@ Notes:
* Setting a property of type Array (or keyed hash) must be an array or an error will be raised. * Setting a property of type Array (or keyed hash) must be an array or an error will be raised.
* Now possible to set Array attribute from hash where keys determine order. * Now possible to set Array attribute from hash where keys determine order.
== 1.0.0.beta5 ## 1.0.0.beta5
* Minor enhancements * Minor enhancements
* Added 'find' alias for 'get' for easier rails transition * Added 'find' alias for 'get' for easier rails transition
== 1.0.0.beta3 ## 1.0.0.beta3
* Minor enhancements * Minor enhancements
* Removed Validation by default, requires too many structure changes (FAIL) * Removed Validation by default, requires too many structure changes (FAIL)
@ -112,12 +175,12 @@ Notes:
* Added support for setting type directly on property (Sam Lown) * Added support for setting type directly on property (Sam Lown)
== 1.0.0.beta2 ## 1.0.0.beta2
* Minor enhancements * Minor enhancements
* Enable Validation by default and refactored location (Sam Lown) * Enable Validation by default and refactored location (Sam Lown)
== 1.0.0.beta ## 1.0.0.beta
* Major enhancements * Major enhancements
* Separated ExtendedDocument from main CouchRest gem (Sam Lown) * Separated ExtendedDocument from main CouchRest gem (Sam Lown)
@ -125,12 +188,12 @@ Notes:
* Minor enhancements * Minor enhancements
* active_support included by default * active_support included by default
== 0.37 ## 0.37
* Minor enhancements * Minor enhancements
* Added gemspec (needed for Bundler install) (Tapajós) * Added gemspec (needed for Bundler install) (Tapajós)
== 0.36 ## 0.36
* Major enhancements * Major enhancements
* Adds support for continuous replication (sauy7) * Adds support for continuous replication (sauy7)
@ -140,7 +203,7 @@ Notes:
* Minor enhancements * Minor enhancements
* Provide a description of the timeout error (John Wood) * Provide a description of the timeout error (John Wood)
== 0.35 ## 0.35
* Major enhancements * Major enhancements
* CouchRest::ExtendedDocument allow chaining the inherit class callback (Kenneth Kalmer) - http://github.com/couchrest/couchrest/issues#issue/8 * CouchRest::ExtendedDocument allow chaining the inherit class callback (Kenneth Kalmer) - http://github.com/couchrest/couchrest/issues#issue/8
@ -156,7 +219,7 @@ Notes:
* Added an update_doc method to database to handle conflicts during atomic updates. (Pierre Larochelle) * Added an update_doc method to database to handle conflicts during atomic updates. (Pierre Larochelle)
* Bug fix: http://github.com/couchrest/couchrest/issues/#issue/2 (Luke Burton) * Bug fix: http://github.com/couchrest/couchrest/issues/#issue/2 (Luke Burton)
== 0.34 ## 0.34
* Major enhancements * Major enhancements
@ -181,7 +244,7 @@ Notes:
* Fix Initialization of ExtendentDocument model shouldn't failed on a nil value in argument (deepj) * Fix Initialization of ExtendentDocument model shouldn't failed on a nil value in argument (deepj)
* Change to use Jeweler and Gemcutter (Marcos Tapajós) * Change to use Jeweler and Gemcutter (Marcos Tapajós)
== 0.33 ## 0.33
* Major enhancements * Major enhancements
@ -196,7 +259,7 @@ Notes:
* Created a new abstraction layer for the REST API (Matt Aimonetti) * Created a new abstraction layer for the REST API (Matt Aimonetti)
* Bug fix: made ExtendedDocument#all compatible with Couch 0.10 (tc) * Bug fix: made ExtendedDocument#all compatible with Couch 0.10 (tc)
== 0.32 ## 0.32
* Major enhancements * Major enhancements
@ -211,7 +274,7 @@ Notes:
* Bug fix: the count method on the proxy collection was missing (Daniel Kirsch) * Bug fix: the count method on the proxy collection was missing (Daniel Kirsch)
* Added #amount_pages to a paginated collection. (Matt Aimonetti) * Added #amount_pages to a paginated collection. (Matt Aimonetti)
== 0.31 ## 0.31
* Major enhancements * Major enhancements
@ -225,7 +288,7 @@ Notes:
* Optimized ExtendedDocument.count to run about 3x faster (Matt Aimonetti) * Optimized ExtendedDocument.count to run about 3x faster (Matt Aimonetti)
* Added Float casting (Ryan Felton & Matt Aimonetti) * Added Float casting (Ryan Felton & Matt Aimonetti)
== 0.30 ## 0.30
* Major enhancements * Major enhancements

View file

@ -153,7 +153,7 @@ module CouchRest
def #{attrib}(reload = false) def #{attrib}(reload = false)
return @#{attrib} unless @#{attrib}.nil? or reload return @#{attrib} unless @#{attrib}.nil? or reload
ary = self.#{options[:foreign_key]}.collect{|i| #{options[:proxy]}.get(i)} ary = self.#{options[:foreign_key]}.collect{|i| #{options[:proxy]}.get(i)}
@#{attrib} = ::CouchRest::CollectionOfProxy.new(ary, self, '#{options[:foreign_key]}') @#{attrib} = ::CouchRest::Model::CollectionOfProxy.new(ary, find_property('#{options[:foreign_key]}'), self)
end end
EOS EOS
end end
@ -161,7 +161,7 @@ module CouchRest
def create_collection_of_setter(attrib, options) def create_collection_of_setter(attrib, options)
class_eval <<-EOS, __FILE__, __LINE__ + 1 class_eval <<-EOS, __FILE__, __LINE__ + 1
def #{attrib}=(value) def #{attrib}=(value)
@#{attrib} = ::CouchRest::CollectionOfProxy.new(value, self, '#{options[:foreign_key]}') @#{attrib} = ::CouchRest::Model::CollectionOfProxy.new(value, find_property('#{options[:foreign_key]}'), self)
end end
EOS EOS
end end
@ -169,67 +169,63 @@ module CouchRest
end end
end end
end
# Special proxy for a collection of items so that adding and removing # Special proxy for a collection of items so that adding and removing
# to the list automatically updates the associated property. # to the list automatically updates the associated property.
class CollectionOfProxy < Array class CollectionOfProxy < CastedArray
attr_accessor :property
attr_accessor :casted_by
def initialize(array, casted_by, property) def initialize(array, property, parent)
self.property = property
self.casted_by = casted_by
(array ||= []).compact! (array ||= []).compact!
casted_by[property.to_s] = [] # replace the original array! super(array, property, parent)
casted_by[casted_by_property.to_s] = [] # replace the original array!
array.compact.each do |obj| array.compact.each do |obj|
check_obj(obj) check_obj(obj)
casted_by[property.to_s] << obj.id casted_by[casted_by_property.to_s] << obj.id
end end
super(array)
end end
def << obj def << obj
check_obj(obj) check_obj(obj)
casted_by[property.to_s] << obj.id casted_by[casted_by_property.to_s] << obj.id
super(obj) super(obj)
end end
def push(obj) def push(obj)
check_obj(obj) check_obj(obj)
casted_by[property.to_s].push obj.id casted_by[casted_by_property.to_s].push obj.id
super(obj) super(obj)
end end
def unshift(obj) def unshift(obj)
check_obj(obj) check_obj(obj)
casted_by[property.to_s].unshift obj.id casted_by[casted_by_property.to_s].unshift obj.id
super(obj) super(obj)
end end
def []= index, obj def []= index, obj
check_obj(obj) check_obj(obj)
casted_by[property.to_s][index] = obj.id casted_by[casted_by_property.to_s][index] = obj.id
super(index, obj) super(index, obj)
end end
def pop def pop
casted_by[property.to_s].pop casted_by[casted_by_property.to_s].pop
super super
end end
def shift def shift
casted_by[property.to_s].shift casted_by[casted_by_property.to_s].shift
super super
end end
protected protected
def check_obj(obj) def check_obj(obj)
raise "Object cannot be added to #{casted_by.class.to_s}##{property.to_s} collection unless saved" if obj.new? raise "Object cannot be added to #{casted_by.class.to_s}##{casted_by_property.to_s} collection unless saved" if obj.new?
end end
end end
end
end end

View file

@ -1,12 +1,12 @@
module CouchRest module CouchRest
module Model module Model
class Base < Document class Base < CouchRest::Document
extend ActiveModel::Naming extend ActiveModel::Naming
include CouchRest::Model::Configuration include CouchRest::Model::Configuration
include CouchRest::Model::Connection
include CouchRest::Model::Persistence include CouchRest::Model::Persistence
include CouchRest::Model::Callbacks
include CouchRest::Model::DocumentQueries include CouchRest::Model::DocumentQueries
include CouchRest::Model::Views include CouchRest::Model::Views
include CouchRest::Model::DesignDoc include CouchRest::Model::DesignDoc
@ -17,9 +17,11 @@ module CouchRest
include CouchRest::Model::PropertyProtection include CouchRest::Model::PropertyProtection
include CouchRest::Model::Associations include CouchRest::Model::Associations
include CouchRest::Model::Validations include CouchRest::Model::Validations
include CouchRest::Model::Callbacks
include CouchRest::Model::Designs include CouchRest::Model::Designs
include CouchRest::Model::CastedBy include CouchRest::Model::CastedBy
include CouchRest::Model::Dirty include CouchRest::Model::Dirty
include CouchRest::Model::Callbacks
def self.subclasses def self.subclasses
@subclasses ||= [] @subclasses ||= []
@ -45,18 +47,24 @@ module CouchRest
# #
# Options supported: # Options supported:
# #
# * :directly_set_attributes: true when data comes directly from database # * :directly_set_attributes, true when data comes directly from database
# * :database: provide an alternative database # * :database, provide an alternative database
# #
def initialize(doc = {}, options = {}) # If a block is provided the new model will be passed into the
doc = prepare_all_attributes(doc, options) # block so that it can be populated.
# set the instances database, if provided def initialize(attributes = {}, options = {})
super()
prepare_all_attributes(attributes, options)
# set the instance's database, if provided
self.database = options[:database] unless options[:database].nil? self.database = options[:database] unless options[:database].nil?
super(doc)
unless self['_id'] && self['_rev'] unless self['_id'] && self['_rev']
self[self.model_type_key] = self.class.to_s self[self.model_type_key] = self.class.to_s
end end
yield self if block_given?
after_initialize if respond_to?(:after_initialize) after_initialize if respond_to?(:after_initialize)
run_callbacks(:initialize) { self }
end end
@ -74,18 +82,19 @@ module CouchRest
super super
end end
## Compatibility with ActiveSupport and older frameworks # compatbility for 1.8, it does not use respond_to_missing?
# thing is, when using it like this only, doing method(:find_by_view)
# Hack so that CouchRest::Document, which descends from Hash, # will throw an error
# doesn't appear to Rails routing as a Hash of options def self.respond_to?(m, include_private = false)
def is_a?(klass) super || respond_to_missing?(m, include_private)
return false if klass == Hash
super
end end
alias :kind_of? :is_a?
def persisted? # ruby 1.9 feature
!new? # this allows ruby to know that the method is defined using
# method_missing, and as such, method(:find_by_view) will actually
# give a Method back, and not throw an error like in 1.8!
def self.respond_to_missing?(m, include_private = false)
has_view?(m) || has_view?(m.to_s[/^find_(by_.+)/, 1])
end end
def to_key def to_key
@ -95,6 +104,26 @@ module CouchRest
alias :to_param :id alias :to_param :id
alias :new_record? :new? alias :new_record? :new?
alias :new_document? :new? alias :new_document? :new?
# Compare this model with another by confirming to see
# if the IDs and their databases match!
#
# Camparison of the database is required in case the
# model has been proxied or loaded elsewhere.
#
# A Basic CouchRest document will only ever compare using
# a Hash comparison on the attributes.
def == other
return false unless other.is_a?(Base)
if id.nil? && other.id.nil?
# no ids? assume comparing nested and revert to hash comparison
to_hash == other.to_hash
else
database == other.database && id == other.id
end
end
alias :eql? :==
end end
end end
end end

View file

@ -5,21 +5,23 @@ module CouchRest #:nodoc:
module Callbacks module Callbacks
extend ActiveSupport::Concern extend ActiveSupport::Concern
CALLBACKS = [
:before_validation, :after_validation,
:after_initialize,
:before_create, :around_create, :after_create,
:before_destroy, :around_destroy, :after_destroy,
:before_save, :around_save, :after_save,
:before_update, :around_update, :after_update,
]
included do included do
extend ActiveModel::Callbacks extend ActiveModel::Callbacks
include ActiveModel::Validations::Callbacks
define_model_callbacks \ define_model_callbacks :initialize, :only => :after
:create, define_model_callbacks :create, :destroy, :save, :update
:destroy,
:save,
:update
end end
def valid?(*) #nodoc
_run_validation_callbacks { super }
end
end end
end end

View file

@ -50,6 +50,22 @@ module CouchRest::Model
super super
end end
def delete(obj)
couchrest_parent_will_change! if use_dirty? && self.length > 0
super(obj)
end
def delete_at(index)
couchrest_parent_will_change! if use_dirty? && self.length > 0
super(index)
end
def build(*args)
obj = casted_by_property.build(*args)
self.push(obj)
obj
end
protected protected
def instantiate_and_cast(obj, change = true) def instantiate_and_cast(obj, change = true)

View file

@ -88,6 +88,13 @@ module CouchRest
end end
alias :find :get alias :find :get
def get!(id)
doc = @klass.get!(id, @database)
doc.database = @database if doc && doc.respond_to?(:database)
doc
end
alias :find! :get!
# Views # Views
def has_view?(view) def has_view?(view)

View file

@ -244,6 +244,7 @@ module CouchRest
else else
options = { :limit => per_page, :skip => per_page * (page - 1) } options = { :limit => per_page, :skip => per_page * (page - 1) }
end end
options[:include_docs] = true
view_options.merge(options) view_options.merge(options)
end end

View file

@ -11,11 +11,27 @@ module CouchRest
add_config :model_type_key add_config :model_type_key
add_config :mass_assign_any_attribute add_config :mass_assign_any_attribute
add_config :auto_update_design_doc add_config :auto_update_design_doc
add_config :environment
add_config :connection
add_config :connection_config_file
configure do |config| configure do |config|
config.model_type_key = 'model' # was 'couchrest-type' config.model_type_key = 'type' # was 'couchrest-type'
config.mass_assign_any_attribute = false config.mass_assign_any_attribute = false
config.auto_update_design_doc = true config.auto_update_design_doc = true
config.environment = :development
config.connection_config_file = File.join(Dir.pwd, 'config', 'couchdb.yml')
config.connection = {
:protocol => 'http',
:host => 'localhost',
:port => '5984',
:prefix => 'couchrest',
:suffix => nil,
:join => '_',
:username => nil,
:password => nil
}
end end
end end

View file

@ -0,0 +1,70 @@
module CouchRest
module Model
module Connection
extend ActiveSupport::Concern
def server
self.class.server
end
module ClassMethods
# Overwrite the normal use_database method so that a database
# name can be provided instead of a full connection.
def use_database(db)
@database = prepare_database(db)
end
# Overwrite the default database method so that it always
# provides something from the configuration
def database
super || (@database ||= prepare_database)
end
def server
@server ||= CouchRest::Server.new(prepare_server_uri)
end
def prepare_database(db = nil)
unless db.is_a?(CouchRest::Database)
conf = connection_configuration
db = [conf[:prefix], db.to_s, conf[:suffix]].reject{|s| s.to_s.empty?}.join(conf[:join])
self.server.database!(db)
else
db
end
end
protected
def prepare_server_uri
conf = connection_configuration
userinfo = [conf[:username], conf[:password]].compact.join(':')
userinfo += '@' unless userinfo.empty?
"#{conf[:protocol]}://#{userinfo}#{conf[:host]}:#{conf[:port]}"
end
def connection_configuration
@connection_configuration ||=
self.connection.update(
(load_connection_config_file[environment.to_sym] || {}).symbolize_keys
)
end
def load_connection_config_file
file = connection_config_file
connection_config_cache[file] ||=
(File.exists?(file) ?
YAML::load(ERB.new(IO.read(file)).result) :
{ }).symbolize_keys
end
def connection_config_cache
Thread.current[:connection_config_cache] ||= {}
end
end
end
end
end

View file

@ -7,7 +7,11 @@ module CouchRest
module ClassMethods module ClassMethods
def design_doc def design_doc
@design_doc ||= ::CouchRest::Design.new(default_design_doc) @design_doc ||= if auto_update_design_doc
::CouchRest::Design.new(default_design_doc)
else
stored_design_doc || ::CouchRest::Design.new(default_design_doc)
end
end end
def design_doc_id def design_doc_id
@ -75,16 +79,25 @@ module CouchRest
# If auto updates enabled, check checksum cache # If auto updates enabled, check checksum cache
return design_doc if auto_update_design_doc && design_doc_cache_checksum(db) == checksum return design_doc if auto_update_design_doc && design_doc_cache_checksum(db) == checksum
retries = 1
begin
# Load up the stored doc (if present), update, and save # Load up the stored doc (if present), update, and save
saved = stored_design_doc(db) saved = stored_design_doc(db)
if saved if saved
if force || saved['couchrest-hash'] != checksum if force || saved['couchrest-hash'] != checksum
saved.merge!(design_doc) saved.merge!(design_doc)
db.save_doc(saved) db.save_doc(saved)
@design_doc = saved # update memo to point to the document we actually saved
end end
else else
design_doc.delete('_rev') # This is a new document and so doesn't have a revision yet
db.save_doc(design_doc) db.save_doc(design_doc)
design_doc.delete('_rev') # Prevent conflicts, never store rev as DB specific end
rescue RestClient::Conflict
# if we get a conflict retry the operation...
raise if retries < 1
retries -= 1
retry
end end
# Ensure checksum cached for next attempt if using auto updates # Ensure checksum cached for next attempt if using auto updates
@ -108,8 +121,6 @@ module CouchRest
} }
end end
end # module ClassMethods end # module ClassMethods
end end

View file

@ -58,13 +58,25 @@ module CouchRest
self.model = model self.model = model
end end
# Define a view and generate a method that will provide a new # Generate a method that will provide a new View instance when
# View instance when requested. # requested. This will also define the view in CouchDB unless
# auto_update_design_doc is disabled.
def view(name, opts = {}) def view(name, opts = {})
View.create(model, name, opts) View.create(model, name, opts) if model.auto_update_design_doc
create_view_method(name) create_view_method(name)
end end
# Really simple design function that allows a filter
# to be added. Filters are simple functions used when listening
# to the _changes feed.
#
# No methods are created here, the design is simply updated.
# See the CouchDB API for more information on how to use this.
def filter(name, function)
filters = (self.model.design_doc['filters'] ||= {})
filters[name.to_s] = function
end
def create_view_method(name) def create_view_method(name)
model.class_eval <<-EOS, __FILE__, __LINE__ + 1 model.class_eval <<-EOS, __FILE__, __LINE__ + 1
def self.#{name}(opts = {}) def self.#{name}(opts = {})

View file

@ -1,10 +1,7 @@
module CouchRest module CouchRest
module Model module Model
module DocumentQueries module DocumentQueries
extend ActiveSupport::Concern
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods module ClassMethods
@ -86,9 +83,12 @@ module CouchRest
# id<String, Integer>:: Document ID # id<String, Integer>:: Document ID
# db<Database>:: optional option to pass a custom database to use # db<Database>:: optional option to pass a custom database to use
def get!(id, db = database) def get!(id, db = database)
raise "Missing or empty document ID" if id.to_s.empty? raise CouchRest::Model::DocumentNotFound if id.blank?
doc = db.get id doc = db.get id
build_from_database(doc) build_from_database(doc)
rescue RestClient::ResourceNotFound
raise CouchRest::Model::DocumentNotFound
end end
alias :find! :get! alias :find! :get!

View file

@ -1,37 +1,37 @@
module CouchRest::Model module CouchRest::Model
module CastedModel module Embeddable
extend ActiveSupport::Concern extend ActiveSupport::Concern
# Include Attributes early to ensure super() will work
include CouchRest::Attributes
included do included do
include CouchRest::Model::Configuration include CouchRest::Model::Configuration
include CouchRest::Model::Callbacks
include CouchRest::Model::Properties include CouchRest::Model::Properties
include CouchRest::Model::PropertyProtection include CouchRest::Model::PropertyProtection
include CouchRest::Model::Associations include CouchRest::Model::Associations
include CouchRest::Model::Validations include CouchRest::Model::Validations
include CouchRest::Model::Callbacks
include CouchRest::Model::CastedBy include CouchRest::Model::CastedBy
include CouchRest::Model::Dirty include CouchRest::Model::Dirty
include CouchRest::Model::Callbacks
class_eval do class_eval do
# Override CastedBy's base_doc? # Override CastedBy's base_doc?
def base_doc? def base_doc?
false # Can never be base doc! false # Can never be base doc!
end end
end end
end end
def initialize(keys = {}) # Initialize a new Casted Model. Accepts the same
raise StandardError unless self.is_a? Hash # options as CouchRest::Model::Base for preparing and initializing
prepare_all_attributes(keys) # attributes.
def initialize(keys = {}, options = {})
super() super()
end prepare_all_attributes(keys, options)
run_callbacks(:initialize) { self }
def []= key, value
super(key.to_s, value)
end
def [] key
super(key.to_s)
end end
# False if the casted model has already # False if the casted model has already
@ -65,6 +65,14 @@ module CouchRest::Model
end end
alias :attributes= :update_attributes_without_saving alias :attributes= :update_attributes_without_saving
end # End Embeddable
# Provide backwards compatability with previous versions (pre 1.1.0)
module CastedModel
extend ActiveSupport::Concern
included do
include CouchRest::Model::Embeddable
end
end end
end end

View file

@ -19,5 +19,7 @@ module CouchRest
end end
end end
end end
class DocumentNotFound < Errors::CouchRestModelError; end
end end
end end

View file

@ -21,14 +21,15 @@ module CouchRest
# Creates the document in the db. Raises an exception # Creates the document in the db. Raises an exception
# if the document is not created properly. # if the document is not created properly.
def create! def create!(options = {})
self.class.fail_validate!(self) unless self.create self.class.fail_validate!(self) unless self.create(options)
end end
# Trigger the callbacks (before, after, around) # Trigger the callbacks (before, after, around)
# only if the document isn't new # only if the document isn't new
def update(options = {}) def update(options = {})
raise "Calling #{self.class.name}#update on document that has not been created!" if self.new? raise "Cannot save a destroyed document!" if destroyed?
raise "Calling #{self.class.name}#update on document that has not been created!" if new?
return false unless perform_validations(options) return false unless perform_validations(options)
return true if !self.disable_dirty && !self.changed? return true if !self.disable_dirty && !self.changed?
_run_update_callbacks do _run_update_callbacks do
@ -54,19 +55,25 @@ module CouchRest
end end
# Deletes the document from the database. Runs the :destroy callbacks. # Deletes the document from the database. Runs the :destroy callbacks.
# Removes the <tt>_id</tt> and <tt>_rev</tt> fields, preparing the
# document to be saved to a new <tt>_id</tt> if required.
def destroy def destroy
_run_destroy_callbacks do _run_destroy_callbacks do
result = database.delete_doc(self) result = database.delete_doc(self)
if result['ok'] if result['ok']
self.delete('_rev') @_destroyed = true
self.delete('_id') self.freeze
end end
result['ok'] result['ok']
end end
end end
def destroyed?
!!@_destroyed
end
def persisted?
!new? && !destroyed?
end
# Update the document's attributes and save. For example: # Update the document's attributes and save. For example:
# #
# doc.update_attributes :name => "Fred" # doc.update_attributes :name => "Fred"
@ -85,11 +92,10 @@ module CouchRest
# #
# Returns self. # Returns self.
def reload def reload
merge!(self.class.get(id)) prepare_all_attributes(database.get(id), :directly_set_attributes => true)
self self
end end
protected protected
def perform_validations(options = {}) def perform_validations(options = {})
@ -105,22 +111,25 @@ module CouchRest
module ClassMethods module ClassMethods
# Creates a new instance, bypassing attribute protection # Creates a new instance, bypassing attribute protection and
# uses the type field to determine which model to use to instanatiate
# the new object.
# #
# ==== Returns # ==== Returns
# a document instance # a document instance
# #
def build_from_database(doc = {}) def build_from_database(doc = {}, options = {}, &block)
base = (doc[model_type_key].blank? || doc[model_type_key] == self.to_s) ? self : doc[model_type_key].constantize src = doc[model_type_key]
base.new(doc, :directly_set_attributes => true) base = (src.blank? || src == self.to_s) ? self : src.constantize
base.new(doc, options.merge(:directly_set_attributes => true), &block)
end end
# Defines an instance and save it directly to the database # Defines an instance and save it directly to the database
# #
# ==== Returns # ==== Returns
# returns the reloaded document # returns the reloaded document
def create(attributes = {}) def create(attributes = {}, &block)
instance = new(attributes) instance = new(attributes, &block)
instance.create instance.create
instance instance
end end
@ -129,8 +138,8 @@ module CouchRest
# #
# ==== Returns # ==== Returns
# returns the reloaded document or raises an exception # returns the reloaded document or raises an exception
def create!(attributes = {}) def create!(attributes = {}, &block)
instance = new(attributes) instance = new(attributes, &block)
instance.create! instance.create!
instance instance
end end

View file

@ -5,25 +5,17 @@ module CouchRest
extend ActiveSupport::Concern extend ActiveSupport::Concern
included do included do
extlib_inheritable_accessor(:properties) unless self.respond_to?(:properties) class_attribute(:properties) unless self.respond_to?(:properties)
extlib_inheritable_accessor(:properties_by_name) unless self.respond_to?(:properties_by_name) class_attribute(:properties_by_name) unless self.respond_to?(:properties_by_name)
self.properties ||= [] self.properties ||= []
self.properties_by_name ||= {} self.properties_by_name ||= {}
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
# Returns the Class properties # Provide an attribute hash ready to be sent to CouchDB but with
# # all the nil attributes removed.
# ==== Returns def as_couch_json
# Array:: the list of properties for model's class super.delete_if{|k,v| v.nil?}
def properties
self.class.properties
end
# Returns all the class's properties as a Hash where the key is the name
# of the property.
def properties_by_name
self.class.properties_by_name
end end
# Returns the Class properties with their values # Returns the Class properties with their values
@ -90,17 +82,18 @@ module CouchRest
self.disable_dirty = dirty self.disable_dirty = dirty
end end
def prepare_all_attributes(doc = {}, options = {}) def prepare_all_attributes(attrs = {}, options = {})
self.disable_dirty = !!options[:directly_set_attributes] self.disable_dirty = !!options[:directly_set_attributes]
apply_all_property_defaults apply_all_property_defaults
if options[:directly_set_attributes] if options[:directly_set_attributes]
directly_set_read_only_attributes(doc) directly_set_read_only_attributes(attrs)
directly_set_attributes(attrs, true)
else else
doc = remove_protected_attributes(doc) attrs = remove_protected_attributes(attrs)
directly_set_attributes(attrs)
end end
res = doc.nil? ? doc : directly_set_attributes(doc)
self.disable_dirty = false self.disable_dirty = false
res self
end end
def find_property!(property) def find_property!(property)
@ -111,16 +104,13 @@ module CouchRest
# Set all the attributes and return a hash with the attributes # Set all the attributes and return a hash with the attributes
# that have not been accepted. # that have not been accepted.
def directly_set_attributes(hash) def directly_set_attributes(hash, mass_assign = false)
hash.reject do |attribute_name, attribute_value| return if hash.nil?
if self.respond_to?("#{attribute_name}=") hash.reject do |key, value|
self.send("#{attribute_name}=", attribute_value) if self.respond_to?("#{key}=")
true self.send("#{key}=", value)
elsif mass_assign_any_attribute # config option elsif mass_assign || mass_assign_any_attribute
self[attribute_name] = attribute_value self[key] = value
true
else
false
end end
end end
end end
@ -140,7 +130,7 @@ module CouchRest
module ClassMethods module ClassMethods
def property(name, *options, &block) def property(name, *options, &block)
raise "Invalid property definition, '#{name}' already used for CouchRest Model type field" if name.to_s == model_type_key.to_s raise "Invalid property definition, '#{name}' already used for CouchRest Model type field" if name.to_s == model_type_key.to_s && CouchRest::Model::Base >= self
opts = { } opts = { }
type = options.shift type = options.shift
if type.class != Hash if type.class != Hash
@ -161,7 +151,6 @@ module CouchRest
# These properties are casted as Time objects, so they should always # These properties are casted as Time objects, so they should always
# be set to UTC. # be set to UTC.
def timestamps! def timestamps!
class_eval <<-EOS, __FILE__, __LINE__
property(:updated_at, Time, :read_only => true, :protected => true, :auto_validation => false) property(:updated_at, Time, :read_only => true, :protected => true, :auto_validation => false)
property(:created_at, Time, :read_only => true, :protected => true, :auto_validation => false) property(:created_at, Time, :read_only => true, :protected => true, :auto_validation => false)
@ -169,7 +158,6 @@ module CouchRest
write_attribute('updated_at', Time.now) write_attribute('updated_at', Time.now)
write_attribute('created_at', Time.now) if object.new? write_attribute('created_at', Time.now) if object.new?
end end
EOS
end end
protected protected
@ -180,8 +168,8 @@ module CouchRest
# check if this property is going to casted # check if this property is going to casted
type = options.delete(:type) || options.delete(:cast_as) type = options.delete(:type) || options.delete(:cast_as)
if block_given? if block_given?
type = Class.new(Hash) do type = Class.new do
include CastedModel include Embeddable
end end
if block.arity == 1 # Traditional, with options if block.arity == 1 # Traditional, with options
type.class_eval { yield type } type.class_eval { yield type }
@ -203,42 +191,32 @@ module CouchRest
# defines the getter for the property (and optional aliases) # defines the getter for the property (and optional aliases)
def create_property_getter(property) def create_property_getter(property)
# meth = property.name define_method(property.name) do
class_eval <<-EOS, __FILE__, __LINE__ + 1 read_attribute(property.name)
def #{property.name}
read_attribute('#{property.name}')
end end
EOS
if ['boolean', TrueClass.to_s.downcase].include?(property.type.to_s.downcase) if ['boolean', TrueClass.to_s.downcase].include?(property.type.to_s.downcase)
class_eval <<-EOS, __FILE__, __LINE__ define_method("#{property.name}?") do
def #{property.name}? value = read_attribute(property.name)
value = read_attribute('#{property.name}')
!(value.nil? || value == false) !(value.nil? || value == false)
end end
EOS
end end
if property.alias if property.alias
class_eval <<-EOS, __FILE__, __LINE__ + 1 alias_method(property.alias, property.name.to_sym)
alias #{property.alias.to_sym} #{property.name.to_sym}
EOS
end end
end end
# defines the setter for the property (and optional aliases) # defines the setter for the property (and optional aliases)
def create_property_setter(property) def create_property_setter(property)
property_name = property.name name = property.name
class_eval <<-EOS
def #{property_name}=(value) define_method("#{name}=") do |value|
write_attribute('#{property_name}', value) write_attribute(name, value)
end end
EOS
if property.alias if property.alias
class_eval <<-EOS alias_method "#{property.alias}=", "#{name}="
alias #{property.alias.to_sym}= #{property_name.to_sym}=
EOS
end end
end end

View file

@ -27,19 +27,15 @@ module CouchRest::Model
if value.nil? if value.nil?
value = [] value = []
elsif [Hash, HashWithIndifferentAccess].include?(value.class) elsif [Hash, HashWithIndifferentAccess].include?(value.class)
# Assume provided as a Hash where key is index! # Assume provided as a params hash where key is index
data = value value = parameter_hash_to_array(value)
value = [ ]
data.keys.sort.each do |k|
value << data[k]
end
elsif !value.is_a?(Array) elsif !value.is_a?(Array)
raise "Expecting an array or keyed hash for property #{parent.class.name}##{self.name}" raise "Expecting an array or keyed hash for property #{parent.class.name}##{self.name}"
end end
arr = value.collect { |data| cast_value(parent, data) } arr = value.collect { |data| cast_value(parent, data) }
# allow casted_by calls to be passed up chain by wrapping in CastedArray # allow casted_by calls to be passed up chain by wrapping in CastedArray
CastedArray.new(arr, self, parent) CastedArray.new(arr, self, parent)
elsif (type == Object || type == Hash) && (value.class == Hash) elsif (type == Object || type == Hash) && (value.is_a?(Hash))
# allow casted_by calls to be passed up chain by wrapping in CastedHash # allow casted_by calls to be passed up chain by wrapping in CastedHash
CastedHash[value, self, parent] CastedHash[value, self, parent]
elsif !value.nil? elsif !value.nil?
@ -47,9 +43,8 @@ module CouchRest::Model
end end
end end
# Cast an individual value, not an array # Cast an individual value
def cast_value(parent, value) def cast_value(parent, value)
raise "An array inside an array cannot be casted, use CastedModel" if value.is_a?(Array)
value = typecast_value(value, self) value = typecast_value(value, self)
associate_casted_value_to_parent(parent, value) associate_casted_value_to_parent(parent, value)
end end
@ -64,8 +59,28 @@ module CouchRest::Model
end end
end end
# Initialize a new instance of a property's type ready to be
# used. If a proc is defined for the init method, it will be used instead of
# a normal call to the class.
def build(*args)
raise StandardError, "Cannot build property without a class" if @type_class.nil?
if @init_method.is_a?(Proc)
@init_method.call(*args)
else
@type_class.send(@init_method, *args)
end
end
private private
def parameter_hash_to_array(source)
value = [ ]
source.keys.each do |k|
value[k.to_i] = source[k]
end
value.compact
end
def associate_casted_value_to_parent(parent, value) def associate_casted_value_to_parent(parent, value)
value.casted_by = parent if value.respond_to?(:casted_by) value.casted_by = parent if value.respond_to?(:casted_by)
value.casted_by_property = self if value.respond_to?(:casted_by_property) value.casted_by_property = self if value.respond_to?(:casted_by_property)

View file

@ -4,8 +4,14 @@ module CouchRest
module Proxyable module Proxyable
extend ActiveSupport::Concern extend ActiveSupport::Concern
def proxy_database
raise StandardError, "Please set the #proxy_database_method" if self.class.proxy_database_method.nil?
@proxy_database ||= self.class.prepare_database(self.send(self.class.proxy_database_method))
end
module ClassMethods module ClassMethods
# Define a collection that will use the base model for the database connection # Define a collection that will use the base model for the database connection
# details. # details.
def proxy_for(assoc_name, options = {}) def proxy_for(assoc_name, options = {})
@ -13,19 +19,19 @@ module CouchRest
options[:class_name] ||= assoc_name.to_s.singularize.camelize options[:class_name] ||= assoc_name.to_s.singularize.camelize
class_eval <<-EOS, __FILE__, __LINE__ + 1 class_eval <<-EOS, __FILE__, __LINE__ + 1
def #{assoc_name} def #{assoc_name}
unless respond_to?('#{db_method}')
raise "Missing ##{db_method} method for proxy"
end
@#{assoc_name} ||= CouchRest::Model::Proxyable::ModelProxy.new(::#{options[:class_name]}, self, self.class.to_s.underscore, #{db_method}) @#{assoc_name} ||= CouchRest::Model::Proxyable::ModelProxy.new(::#{options[:class_name]}, self, self.class.to_s.underscore, #{db_method})
end end
EOS EOS
end end
# Tell this model which other model to use a base for the database
# connection to use.
def proxied_by(model_name, options = {}) def proxied_by(model_name, options = {})
raise "Model can only be proxied once or ##{model_name} already defined" if method_defined?(model_name) || !proxy_owner_method.nil? raise "Model can only be proxied once or ##{model_name} already defined" if method_defined?(model_name) || !proxy_owner_method.nil?
self.proxy_owner_method = model_name self.proxy_owner_method = model_name
attr_accessor :model_proxy attr_accessor :model_proxy
attr_accessor model_name attr_accessor model_name
overwrite_database_reader(model_name)
end end
# Define an a class variable accessor ready to be inherited and unique # Define an a class variable accessor ready to be inherited and unique
@ -34,6 +40,25 @@ module CouchRest
def proxy_owner_method=(name); @proxy_owner_method = name; end def proxy_owner_method=(name); @proxy_owner_method = name; end
def proxy_owner_method; @proxy_owner_method; end def proxy_owner_method; @proxy_owner_method; end
# Define the name of a method to call to determine the name of
# the database to use as a proxy.
def proxy_database_method(name = nil)
@proxy_database_method = name if name
@proxy_database_method
end
private
# Ensure that no attempt is made to autoload a database connection
# by overwriting it to provide a basic accessor.
def overwrite_database_reader(model_name)
class_eval <<-EOS, __FILE__, __LINE__ + 1
def self.database
raise StandardError, "#{self.to_s} database must be accessed via '#{model_name}' proxy"
end
EOS
end
end end
class ModelProxy class ModelProxy
@ -48,12 +73,12 @@ module CouchRest
end end
# Base # Base
def new(*args) def new(attrs = {}, options = {}, &block)
proxy_update(model.new(*args)) proxy_block_update(:new, attrs, options, &block)
end end
def build_from_database(doc = {}) def build_from_database(attrs = {}, options = {}, &block)
proxy_update(model.build_from_database(doc)) proxy_block_update(:build_from_database, attrs, options, &block)
end end
def method_missing(m, *args, &block) def method_missing(m, *args, &block)
@ -145,6 +170,13 @@ module CouchRest
end end
end end
def proxy_block_update(method, *args, &block)
model.send(method, *args) do |doc|
proxy_update(doc)
yield doc if block_given?
end
end
end end
end end
end end

View file

@ -0,0 +1,13 @@
#
# Extend CouchRest's normal database delete! method to ensure any caches are
# also emptied. Given that this is a rare event, and the consequences are not
# very severe, we just completely empty the cache.
#
CouchRest::Database.class_eval do
def delete!
Thread.current[:couchrest_design_cache] = { }
CouchRest.delete @root
end
end

View file

@ -18,7 +18,7 @@ CouchRest::Design.class_eval do
flatten = flatten =
lambda {|r| lambda {|r|
(recurse = lambda {|v| (recurse = lambda {|v|
if v.is_a?(Hash) if v.is_a?(Hash) || v.is_a?(CouchRest::Document)
v.to_a.map{|v| recurse.call(v)}.flatten v.to_a.map{|v| recurse.call(v)}.flatten
elsif v.is_a?(Array) elsif v.is_a?(Array)
v.flatten.map{|v| recurse.call(v)} v.flatten.map{|v| recurse.call(v)}

View file

@ -14,8 +14,7 @@ module CouchRest
elsif [String, TrueClass, Integer, Float, BigDecimal, DateTime, Time, Date, Class].include?(klass) elsif [String, TrueClass, Integer, Float, BigDecimal, DateTime, Time, Date, Class].include?(klass)
send('typecast_to_'+klass.to_s.downcase, value) send('typecast_to_'+klass.to_s.downcase, value)
else else
# Allow the init_method to be defined as a Proc for advanced conversion property.build(value)
property.init_method.is_a?(Proc) ? property.init_method.call(value) : klass.send(property.init_method, value)
end end
end end

View file

@ -13,18 +13,29 @@ module CouchRest
# Validations may be applied to both Model::Base and Model::CastedModel # Validations may be applied to both Model::Base and Model::CastedModel
module Validations module Validations
extend ActiveSupport::Concern extend ActiveSupport::Concern
included do
include ActiveModel::Validations include ActiveModel::Validations
include ActiveModel::Validations::Callbacks
end
# Determine if the document is valid.
#
# @example Is the document valid?
# person.valid?
#
# @example Is the document valid in a context?
# person.valid?(:create)
#
# @param [ Symbol ] context The optional validation context.
#
# @return [ true, false ] True if valid, false if not.
#
def valid?(context = nil)
super context ? context : (new? ? :create : :update)
end
module ClassMethods module ClassMethods
# Validates the associated casted model. This method should not be # Validates the associated casted model. This method should not be
# used within your code as it is automatically included when a CastedModel # used within your code as it is automatically included when a CastedModel
# is used inside the model. # is used inside the model.
#
def validates_casted_model(*args) def validates_casted_model(*args)
validates_with(CastedModelValidator, _merge_attributes(args)) validates_with(CastedModelValidator, _merge_attributes(args))
end end

View file

@ -11,29 +11,33 @@ module CouchRest
# or add one if necessary. # or add one if necessary.
def setup(model) def setup(model)
@model = model @model = model
if options[:view].blank?
attributes.each do |attribute|
opts = merge_view_options(attribute)
if model.respond_to?(:has_view?) && !model.has_view?(opts[:view_name])
opts[:keys] << {:allow_nil => true}
model.view_by(*opts[:keys])
end
end
end
end end
def validate_each(document, attribute, value) def validate_each(document, attribute, value)
keys = [attribute] opts = merge_view_options(attribute)
unless options[:scope].nil?
keys = (options[:scope].is_a?(Array) ? options[:scope] : [options[:scope]]) + keys
end
values = keys.map{|k| document.send(k)}
values = values.first if values.length == 1
view_name = options[:view].nil? ? "by_#{keys.join('_and_')}" : options[:view] values = opts[:keys].map{|k| document.send(k)}
values = values.first if values.length == 1
model = (document.respond_to?(:model_proxy) && document.model_proxy ? document.model_proxy : @model) model = (document.respond_to?(:model_proxy) && document.model_proxy ? document.model_proxy : @model)
# Determine the base of the search # Determine the base of the search
base = options[:proxy].nil? ? model : document.instance_eval(options[:proxy]) base = opts[:proxy].nil? ? model : document.instance_eval(opts[:proxy])
if base.respond_to?(:has_view?) && !base.has_view?(view_name) if base.respond_to?(:has_view?) && !base.has_view?(opts[:view_name])
raise "View #{document.class.name}.#{options[:view]} does not exist!" unless options[:view].nil? raise "View #{document.class.name}.#{opts[:view_name]} does not exist for validation!"
keys << {:allow_nil => true}
model.view_by(*keys)
end end
rows = base.view(view_name, :key => values, :limit => 2, :include_docs => false)['rows'] rows = base.view(opts[:view_name], :key => values, :limit => 2, :include_docs => false)['rows']
return if rows.empty? return if rows.empty?
unless document.new? unless document.new?
@ -47,6 +51,17 @@ module CouchRest
end end
end end
private
def merge_view_options(attr)
keys = [attr]
keys.unshift(*options[:scope]) unless options[:scope].nil?
view_name = options[:view].nil? ? "by_#{keys.join('_and_')}" : options[:view]
options.merge({:keys => keys, :view_name => view_name})
end
end end
end end

View file

@ -72,9 +72,12 @@ module CouchRest
# <tt>spec/couchrest/more/extended_doc_spec.rb</tt>. # <tt>spec/couchrest/more/extended_doc_spec.rb</tt>.
def view_by(*keys) def view_by(*keys)
return unless auto_update_design_doc
opts = keys.pop if keys.last.is_a?(Hash) opts = keys.pop if keys.last.is_a?(Hash)
opts ||= {} opts ||= {}
ducktype = opts.delete(:ducktype) ducktype = opts.delete(:ducktype)
unless ducktype || opts[:map] unless ducktype || opts[:map]
opts[:guards] ||= [] opts[:guards] ||= []
opts[:guards].push "(doc['#{model_type_key}'] == '#{self.to_s}')" opts[:guards].push "(doc['#{model_type_key}'] == '#{self.to_s}')"

View file

@ -1,11 +1,23 @@
require "rails" require "rails"
require "active_model/railtie" require "active_model/railtie"
module CouchrestModel module CouchRest
# = Active Record Railtie class ModelRailtie < Rails::Railtie
class Railtie < Rails::Railtie def self.generator
config.generators.orm :couchrest_model config.respond_to?(:app_generators) ? :app_generators : :generators
config.generators.test_framework :test_unit, :fixture => false end
config.send(generator).orm :couchrest_model
config.send(generator).test_framework :test_unit, :fixture => false
initializer "couchrest_model.configure_default_connection" do
CouchRest::Model::Base.configure do |conf|
conf.environment = Rails.env
conf.connection_config_file = File.join(Rails.root, 'config', 'couchdb.yml')
conf.connection[:prefix] =
Rails.application.class.to_s.underscore.gsub(/\/.*/, '')
end
end
end end
end end

View file

@ -1,7 +1,6 @@
require 'active_model' require 'active_model'
require "active_model/callbacks" require "active_model/callbacks"
require "active_model/conversion" require "active_model/conversion"
require "active_model/deprecated_error_methods"
require "active_model/errors" require "active_model/errors"
require "active_model/naming" require "active_model/naming"
require "active_model/serialization" require "active_model/serialization"
@ -34,7 +33,6 @@ require "couchrest/model/property_protection"
require "couchrest/model/properties" require "couchrest/model/properties"
require "couchrest/model/casted_array" require "couchrest/model/casted_array"
require "couchrest/model/casted_hash" require "couchrest/model/casted_hash"
require "couchrest/model/casted_model"
require "couchrest/model/validations" require "couchrest/model/validations"
require "couchrest/model/callbacks" require "couchrest/model/callbacks"
require "couchrest/model/document_queries" require "couchrest/model/document_queries"
@ -46,19 +44,23 @@ require "couchrest/model/proxyable"
require "couchrest/model/collection" require "couchrest/model/collection"
require "couchrest/model/associations" require "couchrest/model/associations"
require "couchrest/model/configuration" require "couchrest/model/configuration"
require "couchrest/model/connection"
require "couchrest/model/designs" require "couchrest/model/designs"
require "couchrest/model/designs/view" require "couchrest/model/designs/view"
# Monkey patches applied to couchrest # Monkey patches applied to couchrest
require "couchrest/model/support/couchrest_design" require "couchrest/model/support/couchrest_design"
require "couchrest/model/support/couchrest_database"
# Core Extensions # Core Extensions
require "couchrest/model/core_extensions/hash" require "couchrest/model/core_extensions/hash"
require "couchrest/model/core_extensions/time_parsing" require "couchrest/model/core_extensions/time_parsing"
# Base libraries # Base libraries
require "couchrest/model/casted_model" require "couchrest/model/embeddable"
require "couchrest/model/base" require "couchrest/model/base"
# Add rails support *after* everything has loaded
# Add rails support *after* everything has loaded
if defined?(Rails)
require "couchrest/railtie" require "couchrest/railtie"
end

View file

@ -0,0 +1,18 @@
require 'rails/generators/couchrest_model'
module CouchrestModel
module Generators
class ConfigGenerator < Rails::Generators::Base
source_root File.expand_path('../templates', __FILE__)
def app_name
Rails::Application.subclasses.first.parent.to_s.underscore
end
def copy_configuration_file
template 'couchdb.yml', File.join('config', "couchdb.yml")
end
end
end
end

View file

@ -0,0 +1,21 @@
development: &development
protocol: 'http'
host: localhost
port: 5984
prefix: <%= app_name %>
suffix: development
username:
password:
test:
<<: *development
suffix: test
production:
protocol: 'https'
host: localhost
port: 5984
prefix: <%= app_name %>
suffix: production
username: root
password: 123

View file

@ -1,40 +0,0 @@
require File.expand_path('../../spec_helper', __FILE__)
begin
require 'rubygems' unless ENV['SKIP_RUBYGEMS']
require 'active_support/json'
ActiveSupport::JSON.backend = :JSONGem
class PlainParent
class_inheritable_accessor :foo
self.foo = :bar
end
class PlainChild < PlainParent
end
class ExtendedParent < CouchRest::Model::Base
class_inheritable_accessor :foo
self.foo = :bar
end
class ExtendedChild < ExtendedParent
end
describe "Using chained inheritance without CouchRest::Model::Base" do
it "should preserve inheritable attributes" do
PlainParent.foo.should == :bar
PlainChild.foo.should == :bar
end
end
describe "Using chained inheritance with CouchRest::Model::Base" do
it "should preserve inheritable attributes" do
ExtendedParent.foo.should == :bar
ExtendedChild.foo.should == :bar
end
end
rescue LoadError
puts "This spec requires 'active_support/json' to be loaded"
end

10
spec/fixtures/config/couchdb.yml vendored Normal file
View file

@ -0,0 +1,10 @@
development:
protocol: 'https'
host: sample.cloudant.com
port: 443
prefix: project
suffix: text
username: test
password: user

View file

@ -22,6 +22,7 @@ class Article < CouchRest::Model::Base
property :date, Date property :date, Date
property :slug, :read_only => true property :slug, :read_only => true
property :user_id
property :title property :title
property :tags, [String] property :tags, [String]

View file

@ -83,11 +83,25 @@ class WithCallBacks < CouchRest::Model::Base
end end
end end
# Following two fixture classes have __intentionally__ diffent syntax for setting the validation context
class WithContextualValidationOnCreate < CouchRest::Model::Base
use_database TEST_SERVER.default_database
property(:name, String)
validates(:name, :presence => {:on => :create})
end
class WithContextualValidationOnUpdate < CouchRest::Model::Base
use_database TEST_SERVER.default_database
property(:name, String)
validates(:name, :presence => true, :on => :update)
end
class WithTemplateAndUniqueID < CouchRest::Model::Base class WithTemplateAndUniqueID < CouchRest::Model::Base
use_database TEST_SERVER.default_database use_database TEST_SERVER.default_database
unique_id do |model| unique_id do |model|
model['important-field'] model.slug
end end
property :slug
property :preset, :default => 'value' property :preset, :default => 'value'
property :has_no_default property :has_no_default
end end

View file

@ -1,3 +1,5 @@
require 'person'
class Card < CouchRest::Model::Base class Card < CouchRest::Model::Base
# Set the default database to use # Set the default database to use
use_database DB use_database DB

View file

@ -1,6 +1,6 @@
class CatToy < Hash class CatToy
include ::CouchRest::Model::CastedModel include CouchRest::Model::Embeddable
property :name property :name
@ -17,3 +17,7 @@ class Cat < CouchRest::Model::Base
property :number property :number
end end
class ChildCat < Cat
property :mother, Cat
property :siblings, [Cat]
end

View file

@ -1,5 +1,5 @@
require File.join(FIXTURE_PATH, 'more', 'question') require 'question'
require File.join(FIXTURE_PATH, 'more', 'person') require 'person'
class Course < CouchRest::Model::Base class Course < CouchRest::Model::Base
use_database TEST_SERVER.default_database use_database TEST_SERVER.default_database

5
spec/fixtures/models/key_chain.rb vendored Normal file
View file

@ -0,0 +1,5 @@
class KeyChain < CouchRest::Model::Base
use_database(DB)
property(:keys, Hash)
end

4
spec/fixtures/models/membership.rb vendored Normal file
View file

@ -0,0 +1,4 @@
class Membership
include CouchRest::Model::Embeddable
end

View file

@ -1,5 +1,7 @@
class Person < Hash require 'cat'
include ::CouchRest::Model::CastedModel
class Person
include ::CouchRest::Model::Embeddable
property :pet, Cat property :pet, Cat
property :name, [String] property :name, [String]

6
spec/fixtures/models/project.rb vendored Normal file
View file

@ -0,0 +1,6 @@
class Project < CouchRest::Model::Base
use_database DB
property :name, String
timestamps!
view_by :name
end

7
spec/fixtures/models/question.rb vendored Normal file
View file

@ -0,0 +1,7 @@
class Question
include ::CouchRest::Model::Embeddable
property :q
property :a
end

View file

@ -1,5 +1,6 @@
require File.join(FIXTURE_PATH, 'more', 'client') require 'client'
require File.join(FIXTURE_PATH, 'more', 'sale_entry') require 'sale_entry'
class SaleInvoice < CouchRest::Model::Base class SaleInvoice < CouchRest::Model::Base
use_database DB use_database DB

View file

@ -1,7 +0,0 @@
class Question < Hash
include ::CouchRest::Model::CastedModel
property :q
property :a
end

View file

@ -0,0 +1,8 @@
require File.expand_path('../../spec_helper', __FILE__)
describe CouchRest::Model::Validations do
let(:invoice) do
Invoice.new()
end
end

View file

@ -1,11 +1,16 @@
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "lib"))
require "bundler/setup" require "bundler/setup"
require "rubygems" require "rubygems"
require "rspec" # Satisfies Autotest and anyone else not using the Rake tasks require "rspec"
require File.join(File.dirname(__FILE__), '..','lib','couchrest_model') require 'couchrest_model'
# check the following file to see how to use the spec'd features.
unless defined?(FIXTURE_PATH) unless defined?(FIXTURE_PATH)
MODEL_PATH = File.join(File.dirname(__FILE__), "fixtures", "models")
$LOAD_PATH.unshift(MODEL_PATH)
FIXTURE_PATH = File.join(File.dirname(__FILE__), '/fixtures') FIXTURE_PATH = File.join(File.dirname(__FILE__), '/fixtures')
SCRATCH_PATH = File.join(File.dirname(__FILE__), '/tmp') SCRATCH_PATH = File.join(File.dirname(__FILE__), '/tmp')
@ -16,17 +21,6 @@ unless defined?(FIXTURE_PATH)
DB = TEST_SERVER.database(TESTDB) DB = TEST_SERVER.database(TESTDB)
end end
class Basic < CouchRest::Model::Base
use_database TEST_SERVER.default_database
end
def reset_test_db!
DB.recreate! rescue nil
# Reset the Design Cache
Thread.current[:couchrest_design_cache] = {}
DB
end
RSpec.configure do |config| RSpec.configure do |config|
config.before(:all) { reset_test_db! } config.before(:all) { reset_test_db! }
@ -39,6 +33,21 @@ RSpec.configure do |config|
end end
end end
# Require each of the fixture models
Dir[ File.join(MODEL_PATH, "*.rb") ].sort.each { |file| require File.basename(file) }
class Basic < CouchRest::Model::Base
use_database TEST_SERVER.default_database
end
def reset_test_db!
DB.recreate! rescue nil
# Reset the Design Cache
Thread.current[:couchrest_design_cache] = {}
DB
end
def couchdb_lucene_available? def couchdb_lucene_available?
lucene_path = "http://localhost:5985/" lucene_path = "http://localhost:5985/"
url = URI.parse(lucene_path) url = URI.parse(lucene_path)

View file

@ -0,0 +1,30 @@
# encoding: utf-8
require 'spec_helper'
require 'test/unit/assertions'
require 'active_model/lint'
class CompliantModel < CouchRest::Model::Base
end
describe CouchRest::Model::Base do
include Test::Unit::Assertions
include ActiveModel::Lint::Tests
before :each do
@model = CompliantModel.new
end
describe "active model lint tests" do
ActiveModel::Lint::Tests.public_instance_methods.map{|m| m.to_s}.grep(/^test/).each do |m|
example m.gsub('_',' ') do
send m
end
end
end
def model
@model
end
end

View file

@ -1,7 +1,5 @@
# encoding: utf-8 # encoding: utf-8
require File.expand_path('../../spec_helper', __FILE__) require 'spec_helper'
require File.join(FIXTURE_PATH, 'more', 'sale_invoice')
describe "Assocations" do describe "Assocations" do
@ -101,7 +99,7 @@ describe "Assocations" do
it "should create an associated property and collection proxy" do it "should create an associated property and collection proxy" do
@invoice.respond_to?('entry_ids').should be_true @invoice.respond_to?('entry_ids').should be_true
@invoice.respond_to?('entry_ids=').should be_true @invoice.respond_to?('entry_ids=').should be_true
@invoice.entries.class.should eql(::CouchRest::CollectionOfProxy) @invoice.entries.class.should eql(::CouchRest::Model::CollectionOfProxy)
end end
it "should allow replacement of objects" do it "should allow replacement of objects" do
@ -154,6 +152,33 @@ describe "Assocations" do
@invoice.entries.should be_empty @invoice.entries.should be_empty
end end
# Account for dirty tracking
describe "dirty tracking" do
it "should register changes on push" do
@invoice.changed?.should be_false
@invoice.entries << @entries[0]
@invoice.changed?.should be_true
end
it "should register changes on pop" do
@invoice.entries << @entries[0]
@invoice.save
@invoice.changed?.should be_false
@invoice.entries.pop
@invoice.changed?.should be_true
end
it "should register id changes on push" do
@invoice.entry_ids << @entries[0].id
@invoice.changed?.should be_true
end
it "should register id changes on pop" do
@invoice.entry_ids << @entries[0].id
@invoice.save
@invoice.changed?.should be_false
@invoice.entry_ids.pop
@invoice.changed?.should be_true
end
end
describe "proxy" do describe "proxy" do
it "should ensure new entries to proxy are matched" do it "should ensure new entries to proxy are matched" do

View file

@ -1,4 +1,4 @@
require File.expand_path('../../spec_helper', __FILE__) require 'spec_helper'
describe "Model attachments" do describe "Model attachments" do

View file

@ -1,11 +1,5 @@
# encoding: utf-8 # encoding: utf-8
require "spec_helper"
require File.expand_path("../../spec_helper", __FILE__)
require File.join(FIXTURE_PATH, 'more', 'cat')
require File.join(FIXTURE_PATH, 'more', 'article')
require File.join(FIXTURE_PATH, 'more', 'course')
require File.join(FIXTURE_PATH, 'more', 'card')
require File.join(FIXTURE_PATH, 'base')
describe "Model Base" do describe "Model Base" do
@ -44,6 +38,48 @@ describe "Model Base" do
@obj.database.should eql('database') @obj.database.should eql('database')
end end
it "should support initialization block" do
@obj = Basic.new {|b| b.database = 'database'}
@obj.database.should eql('database')
end
it "should only set defined properties" do
@doc = WithDefaultValues.new(:name => 'test', :foo => 'bar')
@doc['name'].should eql('test')
@doc['foo'].should be_nil
end
it "should set all properties with :directly_set_attributes option" do
@doc = WithDefaultValues.new({:name => 'test', :foo => 'bar'}, :directly_set_attributes => true)
@doc['name'].should eql('test')
@doc['foo'].should eql('bar')
end
it "should set the model type" do
@doc = WithDefaultValues.new()
@doc[WithDefaultValues.model_type_key].should eql('WithDefaultValues')
end
it "should call after_initialize method if available" do
@doc = WithAfterInitializeMethod.new
@doc['some_value'].should eql('value')
end
it "should call after_initialize after block" do
@doc = WithAfterInitializeMethod.new {|d| d.some_value = "foo"}
@doc['some_value'].should eql('foo')
end
it "should call after_initialize callback if available" do
klass = Class.new(CouchRest::Model::Base)
klass.class_eval do # for ruby 1.8.7
property :name
after_initialize :set_name
def set_name; self.name = "foobar"; end
end
@doc = klass.new
@doc.name.should eql("foobar")
end
end end
describe "ActiveModel compatability Basic" do describe "ActiveModel compatability Basic" do
@ -85,14 +121,22 @@ describe "Model Base" do
describe "#persisted?" do describe "#persisted?" do
context "when the document is new" do context "when the document is new" do
it "returns false" do it "returns false" do
@obj.persisted?.should == false @obj.persisted?.should be_false
end end
end end
context "when the document is not new" do context "when the document is not new" do
it "returns id" do it "returns id" do
@obj.save @obj.save
@obj.persisted?.should == true @obj.persisted?.should be_true
end
end
context "when the document is destroyed" do
it "returns false" do
@obj.save
@obj.destroy
@obj.persisted?.should be_false
end end
end end
end end
@ -104,7 +148,57 @@ describe "Model Base" do
end end
end end
describe "#destroyed?" do
it "should be present" do
@obj.should respond_to(:destroyed?)
end
it "should return false with new object" do
@obj.destroyed?.should be_false
end
it "should return true after destroy" do
@obj.save
@obj.destroy
@obj.destroyed?.should be_true
end
end
end
describe "comparisons" do
describe "#==" do
context "on saved document" do
it "should be true on same document" do
p = Project.create
p.should eql(p)
end
it "should be true after loading" do
p = Project.create
p.should eql(Project.get(p.id))
end
it "should not be true if databases do not match" do
p = Project.create
p2 = p.dup
p2.stub!(:database).and_return('other')
p.should_not eql(p2)
end
it "should always be false if one document not saved" do
p = Project.create(:name => 'test')
o = Project.new(:name => 'test')
p.should_not eql(o)
end
end
context "with new documents" do
it "should be true when attributes match" do
p = Project.new(:name => 'test')
o = Project.new(:name => 'test')
p.should eql(o)
end
it "should not be true when attributes don't match" do
p = Project.new(:name => 'test')
o = Project.new(:name => 'testing')
p.should_not eql(o)
end
end
end
end end
describe "update attributes without saving" do describe "update attributes without saving" do
@ -227,7 +321,7 @@ describe "Model Base" do
WithTemplateAndUniqueID.all.map{|o| o.destroy} WithTemplateAndUniqueID.all.map{|o| o.destroy}
WithTemplateAndUniqueID.database.bulk_delete WithTemplateAndUniqueID.database.bulk_delete
@tmpl = WithTemplateAndUniqueID.new @tmpl = WithTemplateAndUniqueID.new
@tmpl2 = WithTemplateAndUniqueID.new(:preset => 'not_value', 'important-field' => '1') @tmpl2 = WithTemplateAndUniqueID.new(:preset => 'not_value', 'slug' => '1')
end end
it "should have fields set when new" do it "should have fields set when new" do
@tmpl.preset.should == 'value' @tmpl.preset.should == 'value'
@ -248,10 +342,10 @@ describe "Model Base" do
before(:all) do before(:all) do
WithTemplateAndUniqueID.all.map{|o| o.destroy} WithTemplateAndUniqueID.all.map{|o| o.destroy}
WithTemplateAndUniqueID.database.bulk_delete WithTemplateAndUniqueID.database.bulk_delete
WithTemplateAndUniqueID.new('important-field' => '1').save WithTemplateAndUniqueID.new('slug' => '1').save
WithTemplateAndUniqueID.new('important-field' => '2').save WithTemplateAndUniqueID.new('slug' => '2').save
WithTemplateAndUniqueID.new('important-field' => '3').save WithTemplateAndUniqueID.new('slug' => '3').save
WithTemplateAndUniqueID.new('important-field' => '4').save WithTemplateAndUniqueID.new('slug' => '4').save
end end
it "should find all" do it "should find all" do
rs = WithTemplateAndUniqueID.all rs = WithTemplateAndUniqueID.all
@ -269,9 +363,9 @@ describe "Model Base" do
end end
it ".count should return the number of documents" do it ".count should return the number of documents" do
WithTemplateAndUniqueID.new('important-field' => '1').save WithTemplateAndUniqueID.new('slug' => '1').save
WithTemplateAndUniqueID.new('important-field' => '2').save WithTemplateAndUniqueID.new('slug' => '2').save
WithTemplateAndUniqueID.new('important-field' => '3').save WithTemplateAndUniqueID.new('slug' => '3').save
WithTemplateAndUniqueID.count.should == 3 WithTemplateAndUniqueID.count.should == 3
end end
@ -280,14 +374,14 @@ describe "Model Base" do
describe "finding the first instance of a model" do describe "finding the first instance of a model" do
before(:each) do before(:each) do
@db = reset_test_db! @db = reset_test_db!
WithTemplateAndUniqueID.new('important-field' => '1').save WithTemplateAndUniqueID.new('slug' => '1').save
WithTemplateAndUniqueID.new('important-field' => '2').save WithTemplateAndUniqueID.new('slug' => '2').save
WithTemplateAndUniqueID.new('important-field' => '3').save WithTemplateAndUniqueID.new('slug' => '3').save
WithTemplateAndUniqueID.new('important-field' => '4').save WithTemplateAndUniqueID.new('slug' => '4').save
end end
it "should find first" do it "should find first" do
rs = WithTemplateAndUniqueID.first rs = WithTemplateAndUniqueID.first
rs['important-field'].should == "1" rs['slug'].should == "1"
end end
it "should return nil if no instances are found" do it "should return nil if no instances are found" do
WithTemplateAndUniqueID.all.each {|obj| obj.destroy } WithTemplateAndUniqueID.all.each {|obj| obj.destroy }
@ -365,13 +459,6 @@ describe "Model Base" do
end end
end end
describe "initialization" do
it "should call after_initialize method if available" do
@doc = WithAfterInitializeMethod.new
@doc['some_value'].should eql('value')
end
end
describe "recursive validation on a model" do describe "recursive validation on a model" do
before :each do before :each do
reset_test_db! reset_test_db!

View file

@ -1,7 +1,4 @@
require File.expand_path('../../spec_helper', __FILE__) require "spec_helper"
require File.join(FIXTURE_PATH, 'more', 'cat')
require File.join(FIXTURE_PATH, 'more', 'person')
require File.join(FIXTURE_PATH, 'more', 'card')
class Driver < CouchRest::Model::Base class Driver < CouchRest::Model::Base
use_database TEST_SERVER.default_database use_database TEST_SERVER.default_database

View file

@ -1,4 +1,4 @@
require File.expand_path("../../spec_helper", __FILE__) require "spec_helper"
class UnattachedDoc < CouchRest::Model::Base class UnattachedDoc < CouchRest::Model::Base
# Note: no use_database here # Note: no use_database here
@ -123,6 +123,35 @@ describe "Proxy Class" do
u.respond_to?(:database).should be_false u.respond_to?(:database).should be_false
end end
end end
describe "#get!" do
it "raises exception when passed a nil" do
expect { @us.get!(nil)}.to raise_error(CouchRest::Model::DocumentNotFound)
end
it "raises exception when passed an empty string " do
expect { @us.get!("")}.to raise_error(CouchRest::Model::DocumentNotFound)
end
it "raises exception when document with provided id does not exist" do
expect { @us.get!("thisisnotreallyadocumentid")}.to raise_error(CouchRest::Model::DocumentNotFound)
end
end
describe "#find!" do
it "raises exception when passed a nil" do
expect { @us.find!(nil)}.to raise_error(CouchRest::Model::DocumentNotFound)
end
it "raises exception when passed an empty string " do
expect { @us.find!("")}.to raise_error(CouchRest::Model::DocumentNotFound)
end
it "raises exception when document with provided id does not exist" do
expect { @us.find!("thisisnotreallyadocumentid")}.to raise_error(CouchRest::Model::DocumentNotFound)
end
end
# Sam Lown 2010-04-07 # Sam Lown 2010-04-07
# Removed as unclear why this should happen as before my changes # Removed as unclear why this should happen as before my changes
# this happend by accident, not explicitly. # this happend by accident, not explicitly.

View file

@ -1,5 +1,4 @@
require File.expand_path("../../spec_helper", __FILE__) require "spec_helper"
require File.join(FIXTURE_PATH, 'more', 'article')
describe "Collections" do describe "Collections" do
@ -27,21 +26,20 @@ describe "Collections" do
end end
it "should provide a class method for paginate" do it "should provide a class method for paginate" do
articles = Article.paginate(:design_doc => 'Article', :view_name => 'by_date', articles = Article.paginate(:design_doc => 'Article', :view_name => 'by_date',
:per_page => 3, :descending => true, :key => Date.today, :include_docs => true) :per_page => 3, :descending => true, :key => Date.today)
articles.size.should == 3 articles.size.should == 3
articles = Article.paginate(:design_doc => 'Article', :view_name => 'by_date', articles = Article.paginate(:design_doc => 'Article', :view_name => 'by_date',
:per_page => 3, :page => 2, :descending => true, :key => Date.today, :include_docs => true) :per_page => 3, :page => 2, :descending => true, :key => Date.today)
articles.size.should == 3 articles.size.should == 3
articles = Article.paginate(:design_doc => 'Article', :view_name => 'by_date', articles = Article.paginate(:design_doc => 'Article', :view_name => 'by_date',
:per_page => 3, :page => 3, :descending => true, :key => Date.today, :include_docs => true) :per_page => 3, :page => 3, :descending => true, :key => Date.today)
articles.size.should == 1 articles.size.should == 1
end end
it "should provide a class method for paginated_each" do it "should provide a class method for paginated_each" do
options = { :design_doc => 'Article', :view_name => 'by_date', options = { :design_doc => 'Article', :view_name => 'by_date',
:per_page => 3, :page => 1, :descending => true, :key => Date.today, :per_page => 3, :page => 1, :descending => true, :key => Date.today }
:include_docs => true }
Article.paginated_each(options) do |a| Article.paginated_each(options) do |a|
a.should_not be_nil a.should_not be_nil
end end

View file

@ -1,8 +1,7 @@
# encoding: utf-8 # encoding: utf-8
require File.expand_path('../../spec_helper', __FILE__) require "spec_helper"
require File.join(FIXTURE_PATH, 'more', 'cat')
describe CouchRest::Model::Base do describe CouchRest::Model::Configuration do
before do before do
@class = Class.new(CouchRest::Model::Base) @class = Class.new(CouchRest::Model::Base)
@ -59,7 +58,7 @@ describe CouchRest::Model::Base do
describe "General examples" do describe "General examples" do
before(:all) do before(:all) do
@default_model_key = 'model' @default_model_key = 'model-type'
end end

View file

@ -0,0 +1,148 @@
# encoding: utf-8
require 'spec_helper'
describe CouchRest::Model::Connection do
before do
@class = Class.new(CouchRest::Model::Base)
end
describe "instance methods" do
before :each do
@obj = @class.new
end
describe "#database" do
it "should respond to" do
@obj.should respond_to(:database)
end
it "should provided class's database" do
@obj.class.should_receive :database
@obj.database
end
end
describe "#server" do
it "should respond to method" do
@obj.should respond_to(:server)
end
it "should return class's server" do
@obj.class.should_receive :server
@obj.server
end
end
end
describe "default configuration" do
it "should provide environment" do
@class.environment.should eql(:development)
end
it "should provide connection config file" do
@class.connection_config_file.should eql(File.join(Dir.pwd, 'config', 'couchdb.yml'))
end
it "should provided simple connection details" do
@class.connection[:prefix].should eql('couchrest')
end
end
describe "class methods" do
describe ".use_database" do
it "should respond to" do
@class.should respond_to(:use_database)
end
end
describe ".database" do
it "should respond to" do
@class.should respond_to(:database)
end
it "should provide a database object" do
@class.database.should be_a(CouchRest::Database)
end
it "should provide a database with default name" do
end
end
describe ".server" do
it "should respond to" do
@class.should respond_to(:server)
end
it "should provide a server object" do
@class.server.should be_a(CouchRest::Server)
end
it "should provide a server with default config" do
@class.server.uri.should eql("http://localhost:5984")
end
it "should allow the configuration to be overwritten" do
@class.connection = {
:protocol => "https",
:host => "127.0.0.1",
:port => '5985',
:prefix => 'sample',
:suffix => 'test',
:username => 'foo',
:password => 'bar'
}
@class.server.uri.should eql("https://foo:bar@127.0.0.1:5985")
end
end
describe ".prepare_database" do
it "should respond to" do
@class.should respond_to(:prepare_database)
end
it "should join the database name correctly" do
@class.connection[:suffix] = 'db'
db = @class.prepare_database('test')
db.name.should eql('couchrest_test_db')
end
it "should ignore nil values in database name" do
@class.connection[:suffix] = nil
db = @class.prepare_database('test')
db.name.should eql('couchrest_test')
end
end
describe "protected methods" do
describe ".connection_configuration" do
it "should provide main config by default" do
@class.send(:connection_configuration).should eql(@class.connection)
end
it "should load file if available" do
@class.connection_config_file = File.join(FIXTURE_PATH, 'config', 'couchdb.yml')
hash = @class.send(:connection_configuration)
hash[:protocol].should eql('https')
hash[:host].should eql('sample.cloudant.com')
hash[:join].should eql('_')
end
end
describe ".load_connection_config_file" do
it "should provide an empty hash if config not found" do
@class.send(:load_connection_config_file).should eql({})
end
it "should load file if available" do
@class.connection_config_file = File.join(FIXTURE_PATH, 'config', 'couchdb.yml')
hash = @class.send(:load_connection_config_file)
hash[:development].should_not be_nil
@class.server.uri.should eql("https://test:user@sample.cloudant.com:443")
end
end
end
end
end

View file

@ -1,10 +1,7 @@
# encoding: utf-8 # encoding: utf-8
require 'spec_helper'
require File.expand_path("../../spec_helper", __FILE__) describe CouchRest::Model::DesignDoc do
require File.join(FIXTURE_PATH, 'base')
require File.join(FIXTURE_PATH, 'more', 'article')
describe "Design Documents" do
before :all do before :all do
reset_test_db! reset_test_db!
@ -17,11 +14,11 @@ describe "Design Documents" do
end end
it "should calculate a consistent checksum for model" do it "should calculate a consistent checksum for model" do
WithTemplateAndUniqueID.design_doc.checksum!.should eql('ff6fa2eaf774397391942d51428c1fe2') WithTemplateAndUniqueID.design_doc.checksum!.should eql('caa2b4c27abb82b4e37421de76d96ffc')
end end
it "should calculate checksum for complex model" do it "should calculate checksum for complex model" do
Article.design_doc.checksum!.should eql('fb65c06a76b6141529e31e894ad00b1a') Article.design_doc.checksum!.should eql('70dff8caea143bf40fad09adf0701104')
end end
it "should cache the generated checksum value" do it "should cache the generated checksum value" do
@ -155,42 +152,75 @@ describe "Design Documents" do
Article.by_date Article.by_date
Article.stored_design_doc['_rev'].should eql(orig) Article.stored_design_doc['_rev'].should eql(orig)
end end
it "should recreate the design doc if database deleted" do
Article.database.recreate!
lambda { Article.by_date }.should_not raise_error(RestClient::ResourceNotFound)
end
end end
describe "when auto_update_design_doc false" do describe "when auto_update_design_doc false" do
# We really do need a new class for each of example. If we try
# to use the same class the examples interact with each in ways
# that can hide failures because the design document gets cached
# at the class level.
let(:model_class) {
class_name = "#{example.metadata[:full_description].gsub(/\s+/,'_').camelize}Model"
doc = CouchRest::Document.new("_id" => "_design/#{class_name}")
doc["language"] = "javascript"
doc["views"] = {"all" => {"map" =>
"function(doc) {
if (doc['type'] == 'Article') {
emit(doc['_id'],1);
}
}"},
"by_name" => {"map" =>
"function(doc) {
if ((doc['type'] == '#{class_name}') && (doc['name'] != null)) {
emit(doc['name'], null);
}",
"reduce" =>
"function(keys, values, rereduce) {
return sum(values);
}"}}
before :all do DB.save_doc doc
Article.auto_update_design_doc = false
Article.save_design_doc!
end
after :all do eval <<-KLASS
Article.auto_update_design_doc = true class ::#{class_name} < CouchRest::Model::Base
use_database DB
self.auto_update_design_doc = false
design do
view :by_name
end end
property :name, String
end
KLASS
it "will not send a request for the saved design doc" do class_name.constantize
Article.should_not_receive(:stored_design_doc) }
Article.by_date
end
it "will not update stored design doc if view changed" do it "will not update stored design doc if view changed" do
Article.by_date model_class.by_name
orig = Article.stored_design_doc orig = model_class.stored_design_doc
design = Article.design_doc design = model_class.design_doc
view = design['views']['by_date']['map'] view = design['views']['by_name']['map']
design['views']['by_date']['map'] = view + ' ' design['views']['by_name']['map'] = view + ' '
Article.by_date model_class.by_name
Article.stored_design_doc['_rev'].should eql(orig['_rev']) model_class.stored_design_doc['_rev'].should eql(orig['_rev'])
end end
it "will update stored design if forced" do it "will update stored design if forced" do
Article.by_date model_class.by_name
orig = Article.stored_design_doc orig = model_class.stored_design_doc
design = Article.design_doc design = model_class.design_doc
view = design['views']['by_date']['map'] view = design['views']['by_name']['map']
design['views']['by_date']['map'] = view + ' ' design['views']['by_name']['map'] = view + ' '
Article.save_design_doc! model_class.save_design_doc!
Article.stored_design_doc['_rev'].should_not eql(orig['_rev']) model_class.stored_design_doc['_rev'].should_not eql(orig['_rev'])
end
it "is able to use predefined views" do
model_class.by_name(key: "special").all
end end
end end
end end
@ -198,7 +228,7 @@ describe "Design Documents" do
describe "lazily refreshing the design document" do describe "lazily refreshing the design document" do
before(:all) do before(:all) do
@db = reset_test_db! @db = reset_test_db!
WithTemplateAndUniqueID.new('important-field' => '1').save WithTemplateAndUniqueID.new('slug' => '1').save
end end
it "should not save the design doc twice" do it "should not save the design doc twice" do
WithTemplateAndUniqueID.all WithTemplateAndUniqueID.all

View file

@ -74,7 +74,7 @@ describe "Design View" do
it "should auto generate mapping from name" do it "should auto generate mapping from name" do
lambda { @klass.create(DesignViewModel, 'by_title') }.should_not raise_error lambda { @klass.create(DesignViewModel, 'by_title') }.should_not raise_error
str = @design_doc['views']['by_title']['map'] str = @design_doc['views']['by_title']['map']
str.should include("((doc['model'] == 'DesignViewModel') && (doc['title'] != null))") str.should include("((doc['#{DesignViewModel.model_type_key}'] == 'DesignViewModel') && (doc['title'] != null))")
str.should include("emit(doc['title'], 1);") str.should include("emit(doc['title'], 1);")
str = @design_doc['views']['by_title']['reduce'] str = @design_doc['views']['by_title']['reduce']
str.should include("return sum(values);") str.should include("return sum(values);")

View file

@ -1,10 +1,9 @@
require File.expand_path("../../spec_helper", __FILE__) require "spec_helper"
class DesignModel < CouchRest::Model::Base class DesignModel < CouchRest::Model::Base
end end
describe "Design" do describe CouchRest::Model::Designs do
it "should accessable from model" do it "should accessable from model" do
DesignModel.respond_to?(:design).should be_true DesignModel.respond_to?(:design).should be_true
@ -84,6 +83,36 @@ describe "Design" do
@object.should_receive(:create_view_method).with('test') @object.should_receive(:create_view_method).with('test')
@object.view('test') @object.view('test')
end end
end
context "for model with auto_update_design_doc disabled " do
class ::DesignModelAutoUpdateDesignDocDisabled < ::CouchRest::Model::Base
self.auto_update_design_doc = false
end
describe "#view" do
before :each do
@object = @klass.new(DesignModelAutoUpdateDesignDocDisabled)
end
it "does not attempt to create view" do
CouchRest::Model::Designs::View.should_not_receive(:create)
@object.view('test')
end
end
end
describe "#filter" do
before :each do
@object = @klass.new(DesignModel)
end
it "should add the provided function to the design doc" do
@object.filter(:important, "function(doc, req) { return doc.priority == 'high'; }")
DesignModel.design_doc['filters'].should_not be_empty
DesignModel.design_doc['filters']['important'].should_not be_blank
end
end end

View file

@ -1,12 +1,6 @@
require File.expand_path("../../spec_helper", __FILE__) require "spec_helper"
require File.join(FIXTURE_PATH, 'more', 'cat') class WithCastedModelMixin
require File.join(FIXTURE_PATH, 'more', 'article')
require File.join(FIXTURE_PATH, 'more', 'course')
require File.join(FIXTURE_PATH, 'more', 'card')
require File.join(FIXTURE_PATH, 'base')
class WithCastedModelMixin < Hash
include CouchRest::Model::CastedModel include CouchRest::Model::CastedModel
property :name property :name
property :details, Object, :default => {} property :details, Object, :default => {}
@ -241,6 +235,14 @@ describe "Dirty" do
end end
end end
it "should report changes if an array is popped after reload" do
should_change_array do |array, obj|
obj.reload
obj.keywords.pop
end
end
it "should report no changes if an empty array is popped" do it "should report no changes if an empty array is popped" do
should_not_change_array do |array, obj| should_not_change_array do |array, obj|
array.clear array.clear
@ -249,6 +251,50 @@ describe "Dirty" do
end end
end end
it "should report changes on deletion from an array" do
should_change_array do |array, obj|
array << "keyword"
obj.save!
array.delete_at(0)
end
should_change_array do |array, obj|
array << "keyword"
obj.save!
array.delete("keyword")
end
end
it "should report changes on deletion from an array after reload" do
should_change_array do |array, obj|
array << "keyword"
obj.save!
obj.reload
array.delete_at(0)
end
should_change_array do |array, obj|
array << "keyword"
obj.save!
obj.reload
array.delete("keyword")
end
end
it "should report no changes on deletion from an empty array" do
should_not_change_array do |array, obj|
array.clear
obj.save!
array.delete_at(0)
end
should_not_change_array do |array, obj|
array.clear
obj.save!
array.delete("keyword")
end
end
it "should report changes if an array is pushed" do it "should report changes if an array is pushed" do
should_change_array do |array, obj| should_change_array do |array, obj|
array.push("keyword") array.push("keyword")

View file

@ -1,26 +1,25 @@
# encoding: utf-8 # encoding: utf-8
require "spec_helper"
require File.expand_path('../../spec_helper', __FILE__) class WithCastedModelMixin
require File.join(FIXTURE_PATH, 'more', 'cat') include CouchRest::Model::Embeddable
require File.join(FIXTURE_PATH, 'more', 'person')
require File.join(FIXTURE_PATH, 'more', 'card')
require File.join(FIXTURE_PATH, 'more', 'question')
require File.join(FIXTURE_PATH, 'more', 'course')
class WithCastedModelMixin < Hash
include CouchRest::Model::CastedModel
property :name property :name
property :no_value property :no_value
property :details, Object, :default => {} property :details, Object, :default => {}
property :casted_attribute, WithCastedModelMixin property :casted_attribute, WithCastedModelMixin
end end
class OldFashionedMixin < Hash
include CouchRest::Model::CastedModel
property :name
end
class DummyModel < CouchRest::Model::Base class DummyModel < CouchRest::Model::Base
use_database TEST_SERVER.default_database use_database TEST_SERVER.default_database
raise "Default DB not set" if TEST_SERVER.default_database.nil? raise "Default DB not set" if TEST_SERVER.default_database.nil?
property :casted_attribute, WithCastedModelMixin property :casted_attribute, WithCastedModelMixin
property :keywords, [String] property :keywords, [String]
property :old_casted_attribute, OldFashionedMixin
property :sub_models do |child| property :sub_models do |child|
child.property :title child.property :title
end end
@ -29,8 +28,8 @@ class DummyModel < CouchRest::Model::Base
end end
end end
class WithCastedCallBackModel < Hash class WithCastedCallBackModel
include CouchRest::Model::CastedModel include CouchRest::Model::Embeddable
property :name property :name
property :run_before_validation property :run_before_validation
property :run_after_validation property :run_after_validation
@ -51,19 +50,7 @@ class CastedCallbackDoc < CouchRest::Model::Base
property :callback_model, WithCastedCallBackModel property :callback_model, WithCastedCallBackModel
end end
describe CouchRest::Model::CastedModel do describe CouchRest::Model::Embeddable do
describe "A non hash class including CastedModel" do
it "should fail raising and include error" do
lambda do
class NotAHashButWithCastedModelMixin
include CouchRest::CastedModel
property :name
end
end.should raise_error
end
end
describe "isolated" do describe "isolated" do
before(:each) do before(:each) do
@ -82,7 +69,27 @@ describe CouchRest::Model::CastedModel do
it "should always return base_doc? as false" do it "should always return base_doc? as false" do
@obj.base_doc?.should be_false @obj.base_doc?.should be_false
end end
it "should call after_initialize callback if available" do
klass = Class.new do
include CouchRest::Model::CastedModel
after_initialize :set_name
property :name
def set_name; self.name = "foobar"; end
end
@obj = klass.new
@obj.name.should eql("foobar")
end
it "should allow override of initialize with super" do
klass = Class.new do
include CouchRest::Model::Embeddable
after_initialize :set_name
property :name
def set_name; self.name = "foobar"; end
def initialize(attrs = {}); super(); end
end
@obj = klass.new
@obj.name.should eql("foobar")
end
end end
describe "casted as an attribute, but without a value" do describe "casted as an attribute, but without a value" do
@ -162,6 +169,33 @@ describe CouchRest::Model::CastedModel do
end end
end end
# Basic testing for an old fashioned casted hash
describe "old hash casted as attribute" do
before :each do
@obj = DummyModel.new(:old_casted_attribute => {:name => 'Testing'})
@casted_obj = @obj.old_casted_attribute
end
it "should be available from its parent" do
@casted_obj.should be_an_instance_of(OldFashionedMixin)
end
it "should have the getters defined" do
@casted_obj.name.should == 'Testing'
end
it "should know who casted it" do
@casted_obj.casted_by.should == @obj
end
it "should know which property casted it" do
@casted_obj.casted_by_property.should == @obj.properties.detect{|p| p.to_s == 'old_casted_attribute'}
end
it "should return nil for the unknown attribute" do
@casted_obj["unknown"].should be_nil
end
end
describe "casted as an array of a different type" do describe "casted as an array of a different type" do
before(:each) do before(:each) do
@obj = DummyModel.new(:keywords => ['couch', 'sofa', 'relax', 'canapé']) @obj = DummyModel.new(:keywords => ['couch', 'sofa', 'relax', 'canapé'])

View file

@ -0,0 +1,33 @@
require 'spec_helper'
class PlainParent
class_inheritable_accessor :foo
self.foo = :bar
end
class PlainChild < PlainParent
end
class ExtendedParent < CouchRest::Model::Base
class_inheritable_accessor :foo
self.foo = :bar
end
class ExtendedChild < ExtendedParent
end
describe "Using chained inheritance without CouchRest::Model::Base" do
it "should preserve inheritable attributes" do
PlainParent.foo.should == :bar
PlainChild.foo.should == :bar
end
end
describe "Using chained inheritance with CouchRest::Model::Base" do
it "should preserve inheritable attributes" do
ExtendedParent.foo.should == :bar
ExtendedChild.foo.should == :bar
end
end

View file

@ -1,12 +1,7 @@
# encoding: utf-8 # encoding: utf-8
require File.expand_path('../../spec_helper', __FILE__) require 'spec_helper'
require File.join(FIXTURE_PATH, 'base')
require File.join(FIXTURE_PATH, 'more', 'cat')
require File.join(FIXTURE_PATH, 'more', 'article')
require File.join(FIXTURE_PATH, 'more', 'course')
require File.join(FIXTURE_PATH, 'more', 'card')
describe "Model Persistence" do describe CouchRest::Model::Persistence do
before(:each) do before(:each) do
@obj = WithDefaultValues.new @obj = WithDefaultValues.new
@ -34,8 +29,8 @@ describe "Model Persistence" do
describe "basic saving and retrieving" do describe "basic saving and retrieving" do
it "should work fine" do it "should work fine" do
@obj.name = "should be easily saved and retrieved" @obj.name = "should be easily saved and retrieved"
@obj.save @obj.save!
saved_obj = WithDefaultValues.get(@obj.id) saved_obj = WithDefaultValues.get!(@obj.id)
saved_obj.should_not be_nil saved_obj.should_not be_nil
end end
@ -81,6 +76,18 @@ describe "Model Persistence" do
article.should_not be_new article.should_not be_new
end end
it "yields new instance to block before saving (#create)" do
article = Article.create{|a| a.title = 'my create init block test'}
article.title.should == 'my create init block test'
article.should_not be_new
end
it "yields new instance to block before saving (#create!)" do
article = Article.create{|a| a.title = 'my create bang init block test'}
article.title.should == 'my create bang init block test'
article.should_not be_new
end
it "should trigger the create callbacks" do it "should trigger the create callbacks" do
doc = WithCallBacks.create(:name => 'my other test') doc = WithCallBacks.create(:name => 'my other test')
doc.run_before_create.should be_true doc.run_before_create.should be_true
@ -210,34 +217,34 @@ describe "Model Persistence" do
it "should require the field" do it "should require the field" do
lambda{@templated.save}.should raise_error lambda{@templated.save}.should raise_error
@templated['important-field'] = 'very-important' @templated['slug'] = 'very-important'
@templated.save.should be_true @templated.save.should be_true
end end
it "should save with the id" do it "should save with the id" do
@templated['important-field'] = 'very-important' @templated['slug'] = 'very-important'
@templated.save.should be_true @templated.save.should be_true
t = WithTemplateAndUniqueID.get('very-important') t = WithTemplateAndUniqueID.get('very-important')
t.should == @templated t.should == @templated
end end
it "should not change the id on update" do it "should not change the id on update" do
@templated['important-field'] = 'very-important' @templated['slug'] = 'very-important'
@templated.save.should be_true @templated.save.should be_true
@templated['important-field'] = 'not-important' @templated['slug'] = 'not-important'
@templated.save.should be_true @templated.save.should be_true
t = WithTemplateAndUniqueID.get('very-important') t = WithTemplateAndUniqueID.get('very-important')
t.id.should == @templated.id t.id.should == @templated.id
end end
it "should raise an error when the id is taken" do it "should raise an error when the id is taken" do
@templated['important-field'] = 'very-important' @templated['slug'] = 'very-important'
@templated.save.should be_true @templated.save.should be_true
lambda{WithTemplateAndUniqueID.new('important-field' => 'very-important').save}.should raise_error lambda{WithTemplateAndUniqueID.new('slug' => 'very-important').save}.should raise_error
end end
it "should set the id" do it "should set the id" do
@templated['important-field'] = 'very-important' @templated['slug'] = 'very-important'
@templated.save.should be_true @templated.save.should be_true
@templated.id.should == 'very-important' @templated.id.should == 'very-important'
end end
@ -245,22 +252,31 @@ describe "Model Persistence" do
describe "destroying an instance" do describe "destroying an instance" do
before(:each) do before(:each) do
@dobj = Basic.new @dobj = Event.new
@dobj.save.should be_true @dobj.save.should be_true
end end
it "should return true" do it "should return true" do
result = @dobj.destroy result = @dobj.destroy
result.should be_true result.should be_true
end end
it "should be resavable" do
@dobj.destroy
@dobj.rev.should be_nil
@dobj.id.should be_nil
@dobj.save.should be_true
end
it "should make it go away" do it "should make it go away" do
@dobj.destroy @dobj.destroy
lambda{Basic.get!(@dobj.id)}.should raise_error lambda{Basic.get!(@dobj.id)}.should raise_error(CouchRest::Model::DocumentNotFound)
end
it "should freeze the object" do
@dobj.destroy
# In Ruby 1.9.2 this raises RuntimeError, in 1.8.7 TypeError, D'OH!
lambda { @dobj.subject = "Test" }.should raise_error(StandardError)
end
it "trying to save after should fail" do
@dobj.destroy
lambda { @dobj.save }.should raise_error(StandardError)
lambda{Basic.get!(@dobj.id)}.should raise_error(CouchRest::Model::DocumentNotFound)
end
it "should make destroyed? true" do
@dobj.destroyed?.should be_false
@dobj.destroy
@dobj.destroyed?.should be_true
end end
end end
@ -340,6 +356,27 @@ describe "Model Persistence" do
end end
end end
describe "with contextual validation on ”create”" do
it "should validate only within ”create” context" do
doc = WithContextualValidationOnCreate.new
doc.save.should be_false
doc.name = "Alice"
doc.save.should be_true
doc.update_attributes(:name => nil).should be_true
end
end
describe "with contextual validation on ”update”" do
it "should validate only within ”update” context" do
doc = WithContextualValidationOnUpdate.new
doc.save.should be_true
doc.update_attributes(:name => nil).should be_false
doc.update_attributes(:name => "Bob").should be_true
end
end
describe "save" do describe "save" do
it "should run the after filter after saving" do it "should run the after filter after saving" do
@doc.run_after_save.should be_nil @doc.run_after_save.should be_nil

View file

@ -1,4 +1,4 @@
require File.expand_path("../../spec_helper", __FILE__) require "spec_helper"
describe "Model Attributes" do describe "Model Attributes" do

View file

@ -1,16 +1,7 @@
# encoding: utf-8 # encoding: utf-8
require File.expand_path('../../spec_helper', __FILE__) require 'spec_helper'
require File.join(FIXTURE_PATH, 'more', 'cat')
require File.join(FIXTURE_PATH, 'more', 'person')
require File.join(FIXTURE_PATH, 'more', 'card')
require File.join(FIXTURE_PATH, 'more', 'invoice')
require File.join(FIXTURE_PATH, 'more', 'service')
require File.join(FIXTURE_PATH, 'more', 'event')
require File.join(FIXTURE_PATH, 'more', 'user')
require File.join(FIXTURE_PATH, 'more', 'course')
describe CouchRest::Model::Property do
describe "Model properties" do
before(:each) do before(:each) do
reset_test_db! reset_test_db!
@ -56,7 +47,11 @@ describe "Model properties" do
end end
it "should raise error if property name coincides with model type key" do it "should raise error if property name coincides with model type key" do
lambda { Person.property(Person.model_type_key) }.should raise_error(/already used/) lambda { Cat.property(Cat.model_type_key) }.should raise_error(/already used/)
end
it "should not raise error if property name coincides with model type key on non-model" do
lambda { Person.property(Article.model_type_key) }.should_not raise_error
end end
it "should be auto timestamped" do it "should be auto timestamped" do
@ -67,6 +62,32 @@ describe "Model properties" do
@card.updated_at.should_not be_nil @card.updated_at.should_not be_nil
end end
describe "#as_couch_json" do
it "should provide a simple hash from model" do
@card.as_couch_json.class.should eql(Hash)
end
it "should remove properties from Hash if value is nil" do
@card.last_name = nil
@card.as_couch_json.keys.include?('last_name').should be_false
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 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"
@ -216,6 +237,16 @@ describe "Model properties" do
end end
describe "properties of hash of casted models" do
it "should be able to assign a casted hash to a hash property" do
chain = KeyChain.new
keys = {"House" => "8==$", "Office" => "<>==U"}
chain.keys = keys
chain.keys = chain.keys
chain.keys.should == keys
end
end
describe "properties of array of casted models" do describe "properties of array of casted models" do
before(:each) do before(:each) do
@ -242,9 +273,9 @@ describe "properties of array of casted models" do
end end
it "should allow attribute to be set from hash with ordered keys and sub-hashes" do it "should allow attribute to be set from hash with ordered keys and sub-hashes" do
@course.questions = { '0' => {:q => "Test1"}, '1' => {:q => 'Test2'} } @course.questions = { '10' => {:q => 'Test10'}, '0' => {:q => "Test1"}, '1' => {:q => 'Test2'} }
@course.questions.length.should eql(2) @course.questions.length.should eql(3)
@course.questions.last.q.should eql('Test2') @course.questions.last.q.should eql('Test10')
@course.questions.last.class.should eql(Question) @course.questions.last.class.should eql(Question)
end end
@ -261,7 +292,7 @@ describe "properties of array of casted models" do
it "should raise an error if attempting to set single value for array type" do it "should raise an error if attempting to set single value for array type" do
lambda { lambda {
@course.questions = Question.new(:q => 'test1') @course.questions = Question.new(:q => 'test1')
}.should raise_error }.should raise_error(/Expecting an array/)
end end
@ -292,6 +323,28 @@ describe "a casted model retrieved from the database" do
end end
end end
describe "nested models (not casted)" do
before(:each) do
reset_test_db!
@cat = ChildCat.new(:name => 'Stimpy')
@cat.mother = {:name => 'Stinky'}
@cat.siblings = [{:name => 'Feather'}, {:name => 'Felix'}]
@cat.save
@cat = ChildCat.get(@cat.id)
end
it "should correctly save single relation" do
@cat.mother.name.should eql('Stinky')
@cat.mother.casted_by.should eql(@cat)
end
it "should correctly save collection" do
@cat.siblings.first.name.should eql("Feather")
@cat.siblings.last.casted_by.should eql(@cat)
end
end
describe "Property Class" do describe "Property Class" do
it "should provide name as string" do it "should provide name as string" do
@ -335,6 +388,28 @@ describe "Property Class" do
property.init_method.should eql('parse') property.init_method.should eql('parse')
end end
describe "#build" do
it "should allow instantiation of new object" do
property = CouchRest::Model::Property.new(:test, Date)
obj = property.build(2011, 05, 21)
obj.should eql(Date.new(2011, 05, 21))
end
it "should use init_method if provided" do
property = CouchRest::Model::Property.new(:test, Date, :init_method => 'parse')
obj = property.build("2011-05-21")
obj.should eql(Date.new(2011, 05, 21))
end
it "should use init_method Proc if provided" do
property = CouchRest::Model::Property.new(:test, Date, :init_method => Proc.new{|v| Date.parse(v)})
obj = property.build("2011-05-21")
obj.should eql(Date.new(2011, 05, 21))
end
it "should raise error if no class" do
property = CouchRest::Model::Property.new(:test)
lambda { property.build }.should raise_error(StandardError, /Cannot build/)
end
end
## Property Casting method. More thoroughly tested in typecast_spec. ## Property Casting method. More thoroughly tested in typecast_spec.
describe "casting" do describe "casting" do
@ -363,14 +438,29 @@ describe "Property Class" do
property.cast(parent, ["2010-06-01", "2010-06-02"]).class.should eql(CouchRest::Model::CastedArray) property.cast(parent, ["2010-06-01", "2010-06-02"]).class.should eql(CouchRest::Model::CastedArray)
end end
it "should raise and error if value is array when type is not" do it "should allow instantion of model via CastedArray#build" do
property = CouchRest::Model::Property.new(:test, Date) property = CouchRest::Model::Property.new(:dates, [Date])
parent = mock("FooClass") parent = Article.new
lambda { ary = property.cast(parent, [])
cast = property.cast(parent, [Date.new(2010, 6, 1)]) obj = ary.build(2011, 05, 21)
}.should raise_error ary.length.should eql(1)
ary.first.should eql(Date.new(2011, 05, 21))
obj = ary.build(2011, 05, 22)
ary.length.should eql(2)
ary.last.should eql(Date.new(2011, 05, 22))
end end
it "should cast an object that provides an array" do
prop = Class.new do
attr_accessor :ary
def initialize(val); self.ary = val; end
def as_json; ary; end
end
property = CouchRest::Model::Property.new(:test, prop)
parent = mock("FooClass")
cast = property.cast(parent, [1, 2])
cast.ary.should eql([1, 2])
end
it "should set parent as casted_by object in CastedArray" do it "should set parent as casted_by object in CastedArray" do
property = CouchRest::Model::Property.new(:test, [Object]) property = CouchRest::Model::Property.new(:test, [Object])

View file

@ -1,25 +1,50 @@
require File.expand_path("../../spec_helper", __FILE__) require "spec_helper"
require File.join(FIXTURE_PATH, 'more', 'cat')
class DummyProxyable < CouchRest::Model::Base class DummyProxyable < CouchRest::Model::Base
def proxy_database proxy_database_method :db
'db' # Do not use this! def db
'db'
end end
end end
class ProxyKitten < CouchRest::Model::Base class ProxyKitten < CouchRest::Model::Base
end end
describe "Proxyable" do describe CouchRest::Model::Proxyable do
describe "#proxy_database" do
before do
@class = Class.new(CouchRest::Model::Base)
@class.class_eval do
def slug; 'proxy'; end
end
@obj = @class.new
end
it "should respond to method" do
@obj.should respond_to(:proxy_database)
end
it "should provide proxy database from method" do
@class.stub!(:proxy_database_method).twice.and_return(:slug)
@obj.proxy_database.should be_a(CouchRest::Database)
@obj.proxy_database.name.should eql('couchrest_proxy')
end
it "should raise an error if called and no proxy_database_method set" do
lambda { @obj.proxy_database }.should raise_error(StandardError, /Please set/)
end
end
describe "class methods" do describe "class methods" do
describe ".proxy_owner_method" do
before(:each) do before(:each) do
@class = DummyProxyable.clone @class = DummyProxyable.clone
end end
describe ".proxy_owner_method" do
it "should provide proxy_owner_method accessors" do it "should provide proxy_owner_method accessors" do
@class.should respond_to(:proxy_owner_method) @class.should respond_to(:proxy_owner_method)
@class.should respond_to(:proxy_owner_method=) @class.should respond_to(:proxy_owner_method=)
@ -30,7 +55,20 @@ describe "Proxyable" do
end end
end end
describe ".proxy_database_method" do
before do
@class = Class.new(CouchRest::Model::Base)
end
it "should be possible to set the proxy database method" do
@class.proxy_database_method :db
@class.proxy_database_method.should eql(:db)
end
end
describe ".proxy_for" do describe ".proxy_for" do
before(:each) do
@class = DummyProxyable.clone
end
it "should be provided" do it "should be provided" do
@class.should respond_to(:proxy_for) @class.should respond_to(:proxy_for)
@ -47,8 +85,7 @@ describe "Proxyable" do
DummyProxyable.proxy_for(:cats) DummyProxyable.proxy_for(:cats)
@obj = DummyProxyable.new @obj = DummyProxyable.new
CouchRest::Model::Proxyable::ModelProxy.should_receive(:new).with(Cat, @obj, 'dummy_proxyable', 'db').and_return(true) CouchRest::Model::Proxyable::ModelProxy.should_receive(:new).with(Cat, @obj, 'dummy_proxyable', 'db').and_return(true)
@obj.should_receive('proxy_database').and_return('db') @obj.should_receive(:proxy_database).and_return('db')
@obj.should_receive(:respond_to?).with('proxy_database').and_return(true)
@obj.cats @obj.cats
end end
@ -60,26 +97,16 @@ describe "Proxyable" do
@obj = DummyProxyable.new @obj = DummyProxyable.new
CouchRest::Model::Proxyable::ModelProxy.should_receive(:new).with(::Document, @obj, 'dummy_proxyable', 'db').and_return(true) CouchRest::Model::Proxyable::ModelProxy.should_receive(:new).with(::Document, @obj, 'dummy_proxyable', 'db').and_return(true)
@obj.should_receive('proxy_database').and_return('db') @obj.should_receive('proxy_database').and_return('db')
@obj.should_receive(:respond_to?).with('proxy_database').and_return(true)
@obj.documents @obj.documents
end end
it "should raise an error if the database method is missing" do
@class.proxy_for(:cats)
@obj = @class.new
@obj.should_receive(:respond_to?).with('proxy_database').and_return(false)
lambda { @obj.cats }.should raise_error(StandardError, "Missing #proxy_database method for proxy")
end
it "should raise an error if custom database method missing" do
@class.proxy_for(:proxy_kittens, :database_method => "foobardom")
@obj = @class.new
lambda { @obj.proxy_kittens }.should raise_error(StandardError, "Missing #foobardom method for proxy")
end
end end
end end
describe ".proxied_by" do describe ".proxied_by" do
before do
@class = Class.new(CouchRest::Model::Base)
end
it "should be provided" do it "should be provided" do
@class.should respond_to(:proxied_by) @class.should respond_to(:proxied_by)
end end
@ -107,6 +134,11 @@ describe "Proxyable" do
@class.proxied_by(:department) @class.proxied_by(:department)
lambda { @class.proxied_by(:company) }.should raise_error lambda { @class.proxied_by(:company) }.should raise_error
end end
it "should overwrite the database method to provide an error" do
@class.proxied_by(:company)
lambda { @class.database }.should raise_error(StandardError, /database must be accessed via/)
end
end end
end end
@ -131,15 +163,13 @@ describe "Proxyable" do
end end
it "should proxy new call" do it "should proxy new call" do
Cat.should_receive(:new).and_return({}) @obj.should_receive(:proxy_block_update).with(:new, 'attrs', 'opts')
@obj.should_receive(:proxy_update).and_return(true) @obj.new('attrs', 'opts')
@obj.new
end end
it "should proxy build_from_database" do it "should proxy build_from_database" do
Cat.should_receive(:build_from_database).and_return({}) @obj.should_receive(:proxy_block_update).with(:build_from_database, 'attrs', 'opts')
@obj.should_receive(:proxy_update).with({}).and_return(true) @obj.build_from_database('attrs', 'opts')
@obj.build_from_database
end end
describe "#method_missing" do describe "#method_missing" do
@ -279,6 +309,15 @@ describe "Proxyable" do
@obj.send(:proxy_update_all, docs) @obj.send(:proxy_update_all, docs)
end end
describe "#proxy_block_update" do
it "should proxy block updates" do
doc = { }
@obj.model.should_receive(:new).and_yield(doc)
@obj.should_receive(:proxy_update).with(doc)
@obj.send(:proxy_block_update, :new)
end
end
end end
end end
@ -316,7 +355,7 @@ describe "Proxyable" do
it "should allow creation of new entries" do it "should allow creation of new entries" do
inv = @company.proxyable_invoices.new(:client => "Lorena", :total => 35) inv = @company.proxyable_invoices.new(:client => "Lorena", :total => 35)
inv.database.should_not be_nil # inv.database.should_not be_nil
inv.save.should be_true inv.save.should be_true
@company.proxyable_invoices.count.should eql(1) @company.proxyable_invoices.count.should eql(1)
@company.proxyable_invoices.first.client.should eql("Lorena") @company.proxyable_invoices.first.client.should eql("Lorena")

View file

@ -1,8 +1,4 @@
require File.expand_path("../../spec_helper", __FILE__) require "spec_helper"
require File.join(FIXTURE_PATH, 'more', 'cat')
require File.join(FIXTURE_PATH, 'more', 'person')
require File.join(FIXTURE_PATH, 'more', 'card')
require File.join(FIXTURE_PATH, 'more', 'course')
# add a default value # add a default value
Card.property :bg_color, :default => '#ccc' Card.property :bg_color, :default => '#ccc'

View file

@ -1,8 +1,5 @@
# encoding: utf-8 # encoding: utf-8
require File.expand_path('../../spec_helper', __FILE__) require 'spec_helper'
require File.join(FIXTURE_PATH, 'more', 'cat')
require File.join(FIXTURE_PATH, 'more', 'person')
require File.join(FIXTURE_PATH, 'more', 'course')
describe "Type Casting" do describe "Type Casting" do

View file

@ -1,14 +1,6 @@
require File.expand_path("../../spec_helper", __FILE__) require "spec_helper"
require File.join(FIXTURE_PATH, 'more', 'cat') describe CouchRest::Model::Validations do
require File.join(FIXTURE_PATH, 'more', 'article')
require File.join(FIXTURE_PATH, 'more', 'course')
require File.join(FIXTURE_PATH, 'more', 'card')
require File.join(FIXTURE_PATH, 'base')
# TODO Move validations from other specs to here
describe "Validations" do
describe "Uniqueness" do describe "Uniqueness" do
@ -17,6 +9,10 @@ describe "Validations" do
@objs = ['title 1', 'title 2', 'title 3'].map{|t| WithUniqueValidation.create(:title => t)} @objs = ['title 1', 'title 2', 'title 3'].map{|t| WithUniqueValidation.create(:title => t)}
end end
it "should create a new view if none defined before performing" do
WithUniqueValidation.has_view?(:by_title).should be_true
end
it "should validate a new unique document" do it "should validate a new unique document" do
@obj = WithUniqueValidation.create(:title => 'title 4') @obj = WithUniqueValidation.create(:title => 'title 4')
@obj.new?.should_not be_true @obj.new?.should_not be_true
@ -35,6 +31,7 @@ describe "Validations" do
@obj.should be_valid @obj.should be_valid
end end
it "should allow own view to be specified" do it "should allow own view to be specified" do
# validates_uniqueness_of :code, :view => 'all' # validates_uniqueness_of :code, :view => 'all'
WithUniqueValidationView.create(:title => 'title 1', :code => '1234') WithUniqueValidationView.create(:title => 'title 1', :code => '1234')
@ -50,6 +47,13 @@ describe "Validations" do
}.should raise_error }.should raise_error
end end
it "should not try to create a defined view" do
WithUniqueValidationView.validates_uniqueness_of :title, :view => 'fooobar'
WithUniqueValidationView.has_view?('fooobar').should be_false
WithUniqueValidationView.has_view?('by_title').should be_false
end
it "should not try to create new view when already defined" do it "should not try to create new view when already defined" do
@obj = @objs[1] @obj = @objs[1]
@obj.class.should_not_receive('view_by') @obj.class.should_not_receive('view_by')
@ -60,6 +64,11 @@ describe "Validations" do
end end
context "with a proxy parameter" do context "with a proxy parameter" do
it "should create a new view despite proxy" do
WithUniqueValidationProxy.has_view?(:by_title).should be_true
end
it "should be used" do it "should be used" do
@obj = WithUniqueValidationProxy.new(:title => 'test 6') @obj = WithUniqueValidationProxy.new(:title => 'test 6')
proxy = @obj.should_receive('proxy').and_return(@obj.class) proxy = @obj.should_receive('proxy').and_return(@obj.class)

View file

@ -1,19 +1,18 @@
require File.expand_path("../../spec_helper", __FILE__) require "spec_helper"
require File.join(FIXTURE_PATH, 'more', 'cat')
require File.join(FIXTURE_PATH, 'more', 'person')
require File.join(FIXTURE_PATH, 'more', 'article')
require File.join(FIXTURE_PATH, 'more', 'course')
describe "Model views" do describe CouchRest::Model::Views do
class Unattached < CouchRest::Model::Base class Unattached < CouchRest::Model::Base
# Note: no use_database here
property :title property :title
property :questions property :questions
property :professor property :professor
view_by :title view_by :title
end
# Force the database to always be nil
def self.database
nil
end
end
describe "ClassMethods" do describe "ClassMethods" do
# NOTE! Add more unit tests! # NOTE! Add more unit tests!
@ -175,6 +174,21 @@ describe "Model views" do
end end
describe "#method_missing for find_by methods" do
before(:all) { reset_test_db! }
specify { Course.should respond_to :find_by_title_and_active }
specify { Course.should respond_to :by_title }
specify "#method should work in ruby 1.9, but not 1.8" do
if RUBY_VERSION >= "1.9"
Course.method(:find_by_title_and_active).should be_a Method
else
expect { Course.method(:find_by_title_and_active) }.to raise_error(NameError)
end
end
end
describe "a ducktype view" do describe "a ducktype view" do
before(:all) do before(:all) do
reset_test_db! reset_test_db!
@ -195,7 +209,7 @@ describe "Model views" do
end end
end end
describe "a model class not tied to a database" do describe "a model class with database provided manually" do
before(:all) do before(:all) do
reset_test_db! reset_test_db!
@db = DB @db = DB