Compare commits

..

No commits in common. "master" and "adv_design" have entirely different histories.

91 changed files with 2530 additions and 4345 deletions

6
.gitignore vendored
View file

@ -2,10 +2,8 @@
html/* html/*
pkg pkg
*.swp *.swp
.rvmrc* .rvmrc
.bundle .bundle
couchdb.std* couchdb.std*
*.*~ *.*~
Gemfile.lock
spec.out
*.gem

76
Gemfile.lock Normal file
View file

@ -0,0 +1,76 @@
PATH
remote: .
specs:
couchrest_model (1.1.0.beta)
activemodel (~> 3.0.0)
couchrest (~> 1.0.2)
mime-types (~> 1.15)
railties (~> 3.0.0)
tzinfo (~> 0.3.22)
GEM
remote: http://rubygems.org/
specs:
abstract (1.0.0)
actionpack (3.0.4)
activemodel (= 3.0.4)
activesupport (= 3.0.4)
builder (~> 2.1.2)
erubis (~> 2.6.6)
i18n (~> 0.4)
rack (~> 1.2.1)
rack-mount (~> 0.6.13)
rack-test (~> 0.5.7)
tzinfo (~> 0.3.23)
activemodel (3.0.4)
activesupport (= 3.0.4)
builder (~> 2.1.2)
i18n (~> 0.4)
activesupport (3.0.4)
builder (2.1.2)
couchrest (1.0.2)
json (~> 1.5.1)
mime-types (~> 1.15)
rest-client (~> 1.6.1)
diff-lcs (1.1.2)
erubis (2.6.6)
abstract (>= 1.0.0)
i18n (0.5.0)
json (1.5.1)
mime-types (1.16)
rack (1.2.1)
rack-mount (0.6.13)
rack (>= 1.0.0)
rack-test (0.5.7)
rack (>= 1.0)
railties (3.0.4)
actionpack (= 3.0.4)
activesupport (= 3.0.4)
rake (>= 0.8.7)
thor (~> 0.14.4)
rake (0.8.7)
rest-client (1.6.1)
mime-types (>= 1.16)
rspec (2.2.0)
rspec-core (~> 2.2)
rspec-expectations (~> 2.2)
rspec-mocks (~> 2.2)
rspec-core (2.3.0)
rspec-expectations (2.3.0)
diff-lcs (~> 1.1.2)
rspec-mocks (2.3.0)
thor (0.14.6)
tzinfo (0.3.24)
PLATFORMS
ruby
DEPENDENCIES
activemodel (~> 3.0.0)
couchrest (~> 1.0.2)
couchrest_model!
mime-types (~> 1.15)
rack-test (>= 0.5.7)
railties (~> 3.0.0)
rspec (>= 2.0.0)
tzinfo (~> 0.3.22)

512
README.md
View file

@ -3,16 +3,6 @@
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.
@ -21,14 +11,6 @@ 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 '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|
config.model_type_key = 'couchrest-type'
end
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
### Gem ### Gem
@ -41,43 +23,43 @@ If you're using bundler, define a line similar to the following in your project'
gem 'couchrest_model' gem 'couchrest_model'
### Configuration 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.
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. gem 'couchrest_model', :git => 'git://github.com/couchrest/couchrest_model.git'
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: ### Setup
development: 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.
protocol: 'https'
host: sample.cloudant.com
port: 443
prefix: project
suffix: test
username: test
password: user
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. TODO: Add an example!
The example config above for example would use a database called "project_test". Heres an example using the `use_database` call: ### Development
class Project < CouchRest::Model::Base 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:
use_database 'sample'
end
# The database object would be provided as: bundle install
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)
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'
@ -109,22 +91,453 @@ The example config above for example would use a database called "project_test".
@cat.new? # false @cat.new? # false
@cat.random_text # Raises error! @cat.random_text # Raises error!
## Development
### Preparations ## Properties
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: A property is the definition of an attribute, it describes what the attribute is called, how it should
be type casted and other options such as the default value. These replace your typical
`add_column` methods found in relational database migrations.
bundle install Attributes with a property definition will have setter and getter methods defined for them. Any other attibute
can be set as if the model were a Hash, this funcionality is inherited from CouchRest Documents.
That should set everything up for `rake spec` to be run correctly. Update the couchrest_model.gemspec if your alterations Here are a few examples of the way properties are used:
use different gems.
### Testing class Cat < CouchRest::Model::Base
property :name
property :birthday
end
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 = Cat.new(:name => 'Felix', :birthday => 2.years.ago)
@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
## 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!
## 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 loading code:
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` - 'couchrest-type' by default, is the name of property that holds the class name of each CouchRest Model.
## 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
@ -134,4 +547,3 @@ 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,18 +1,21 @@
require 'rubygems' require 'rubygems'
require 'bundler' require 'bundler'
require 'rspec/core/rake_task'
require "rake/rdoctask"
Bundler::GemHelper.install_tasks Bundler::GemHelper.install_tasks
require 'rake'
require "rake/rdoctask"
require 'rspec'
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.2 1.1.0.beta

View file

@ -1,118 +0,0 @@
#!/usr/bin/env ruby
require 'rubygems'
require 'benchmark'
$:.unshift(File.dirname(__FILE__) + '/../lib')
require 'couchrest_model'
class BenchmarkCasted < Hash
include CouchRest::Model::CastedModel
property :name
end
class BenchmarkModel < CouchRest::Model::Base
use_database CouchRest.database!(ENV['BENCHMARK_DB'] || "http://localhost:5984/test")
property :string, String
property :number, Integer
property :casted, BenchmarkCasted
property :casted_list, [BenchmarkCasted]
end
# set dirty configuration, return previous configuration setting
def set_dirty(value)
orig = nil
CouchRest::Model::Base.configure do |config|
orig = config.use_dirty
config.use_dirty = value
end
BenchmarkModel.instance_eval do
self.use_dirty = value
end
orig
end
def supports_dirty?
CouchRest::Model::Base.respond_to?(:use_dirty)
end
def run_benchmark
n = 50000 # property operation count
db_n = 1000 # database operation count
b = BenchmarkModel.new
Benchmark.bm(30) do |x|
# property assigning
x.report("assign string:") do
n.times { b.string = "test" }
end
next if ENV["BENCHMARK_STRING"]
x.report("assign integer:") do
n.times { b.number = 1 }
end
x.report("assign casted hash:") do
n.times { b.casted = { 'name' => 'test' } }
end
x.report("assign casted hash list:") do
n.times { b.casted_list = [{ 'name' => 'test' }] }
end
# property reading
x.report("read string") do
n.times { b.string }
end
x.report("read integer") do
n.times { b.number }
end
x.report("read casted hash") do
n.times { b.casted }
end
x.report("read casted hash list") do
n.times { b.casted_list }
end
if ENV['BENCHMARK_DB']
# db writing
x.report("write changed record to db") do
db_n.times { |i| b.string = "test#{i}"; b.save }
end
x.report("write unchanged record to db") do
db_n.times { b.save }
end
# db reading
x.report("read record from db") do
db_n.times { BenchmarkModel.find(b.id) }
end
end
end
end
begin
if supports_dirty?
if !ENV['BENCHMARK_DIRTY_OFF']
set_dirty(true)
puts "with use_dirty true"
run_benchmark
end
set_dirty(false)
puts "\nwith use_dirty false"
end
run_benchmark
end

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 = File.mtime('VERSION') s.date = %q{2011-01-16}
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,14 +23,12 @@ 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.2") s.add_dependency(%q<couchrest>, "~> 1.0.2")
s.add_dependency(%q<mime-types>, "~> 1.15") s.add_dependency(%q<mime-types>, "~> 1.15")
s.add_dependency(%q<activemodel>, "~> 3.0") s.add_dependency(%q<activemodel>, "~> 3.0.0")
s.add_dependency(%q<tzinfo>, "~> 0.3.22") s.add_dependency(%q<tzinfo>, "~> 0.3.22")
s.add_development_dependency(%q<rspec>, "~> 2.6.0") s.add_dependency(%q<railties>, "~> 3.0.0")
s.add_development_dependency(%q<json>, ["~> 1.5.1"]) s.add_development_dependency(%q<rspec>, ">= 2.0.0")
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")
end end

View file

@ -1,92 +1,4 @@
# CouchRest Model Change History == 1.1.0.beta
## 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:
* Fast Dirty Tracking! Many thanks to @sobakasu (Andrew Williams)
* Default CouchRest Model type field now set to 'model' instead of 'couchrest-type'.
* Minor enhancements:
* Adding "couchrest-hash" to Design Docs with aim to improve view update handling.
* Major changes to the way design document updates are handled internally.
* Added "auto_update_design_doc" configuration option.
* Using #descending on View object will automatically swap startkey with endkey.
## 1.1.0.beta3
* Removed
## 1.1.0.beta2
* Minor enhancements:
* Time handling improved in accordance with CouchRest 1.1.0. Always set to UTC.
* Refinements to associations and uniqueness validation for proxy (based on issue found by Gleb Kanterov)
* Added :allow_nil and :allow_blank options when creating a new view
* Unique Validation now supports scopes!
* Added support for #keys with list on Design View.
## 1.1.0.beta
* Epic enhancements: * Epic enhancements:
* Added "View" object for dynamic view queries * Added "View" object for dynamic view queries
@ -97,10 +9,9 @@
* Narrow the rescued exception to avoid catching class evaluation errors that has nothing to to with the association (thanks Simone Carletti) * Narrow the rescued exception to avoid catching class evaluation errors that has nothing to to with the association (thanks Simone Carletti)
* Fix validate uniqueness test that was never executed (thanks Simone Carletti) * Fix validate uniqueness test that was never executed (thanks Simone Carletti)
* Adds a #reload method to reload document attributes (thanks Simone Carletti) * Adds a #reload method to reload document attributes (thanks Simone Carletti)
* 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
@ -119,7 +30,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
@ -130,7 +41,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
@ -146,7 +57,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
@ -160,12 +71,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)
@ -175,12 +86,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)
@ -188,12 +99,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)
@ -203,7 +114,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
@ -219,7 +130,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
@ -244,7 +155,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
@ -259,7 +170,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
@ -274,7 +185,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
@ -288,7 +199,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

@ -12,36 +12,29 @@ module CouchRest
# Define an association that this object belongs to. # Define an association that this object belongs to.
# #
# An attribute will be created matching the name of the attribute
# with '_id' on the end, or the foreign key (:foreign_key) provided.
#
# Searching for the assocated object is performed using a string
# (:proxy) to be evaulated in the context of the owner. Typically
# this will be set to the class name (:class_name), or determined
# automatically if the owner belongs to a proxy object.
#
# If the association owner is proxied by another model, than an attempt will
# be made to automatically determine the correct place to request
# the documents. Typically, this is a method with the pluralized name of the
# association inside owner's owner, or proxy.
#
# For example, imagine a company acts as a proxy for invoices and clients.
# If an invoice belongs to a client, the invoice will need to access the
# list of clients via the proxy. So a request to search for the associated
# client from an invoice would look like:
#
# self.company.clients
#
# If the name of the collection proxy is not the pluralized assocation name,
# it can be set with the :proxy_name option.
#
def belongs_to(attrib, *options) def belongs_to(attrib, *options)
opts = merge_belongs_to_association_options(attrib, options.first) opts = {
:foreign_key => attrib.to_s + '_id',
:class_name => attrib.to_s.camelcase,
:proxy => nil
}
case options.first
when Hash
opts.merge!(options.first)
end
property(opts[:foreign_key], opts) begin
opts[:class] = opts[:class_name].constantize
rescue NameError
raise NameError, "Unable to convert class name into Constant for #{self.name}##{attrib}"
end
create_belongs_to_getter(attrib, opts) prop = property(opts[:foreign_key], opts)
create_belongs_to_setter(attrib, opts)
create_belongs_to_getter(attrib, prop, opts)
create_belongs_to_setter(attrib, prop, opts)
prop
end end
# Provide access to a collection of objects where the associated # Provide access to a collection of objects where the associated
@ -84,50 +77,44 @@ module CouchRest
# frequently! Use with prudence. # frequently! Use with prudence.
# #
def collection_of(attrib, *options) def collection_of(attrib, *options)
opts = merge_belongs_to_association_options(attrib, options.first) opts = {
opts[:foreign_key] = opts[:foreign_key].pluralize :foreign_key => attrib.to_s.singularize + '_ids',
:class_name => attrib.to_s.singularize.camelcase,
:proxy => nil
}
case options.first
when Hash
opts.merge!(options.first)
end
begin
opts[:class] = opts[:class_name].constantize
rescue
raise "Unable to convert class name into Constant for #{self.name}##{attrib}"
end
opts[:readonly] = true opts[:readonly] = true
property(opts[:foreign_key], [], opts) prop = property(opts[:foreign_key], [], opts)
create_collection_of_property_setter(attrib, opts) create_collection_of_property_setter(attrib, prop, opts)
create_collection_of_getter(attrib, opts) create_collection_of_getter(attrib, prop, opts)
create_collection_of_setter(attrib, opts) create_collection_of_setter(attrib, prop, opts)
prop
end end
private private
def merge_belongs_to_association_options(attrib, options = nil) def create_belongs_to_getter(attrib, property, options)
opts = { base = options[:proxy] || options[:class_name]
:foreign_key => attrib.to_s.singularize + '_id',
:class_name => attrib.to_s.singularize.camelcase,
:proxy_name => attrib.to_s.pluralize
}
opts.merge!(options) if options.is_a?(Hash)
# Generate a string for the proxy method call
# Assumes that the proxy_owner_method from "proxyable" is available.
if opts[:proxy].to_s.empty?
opts[:proxy] = if proxy_owner_method
"self.#{proxy_owner_method}.#{opts[:proxy_name]}"
else
opts[:class_name]
end
end
opts
end
def create_belongs_to_getter(attrib, options)
class_eval <<-EOS, __FILE__, __LINE__ + 1 class_eval <<-EOS, __FILE__, __LINE__ + 1
def #{attrib} def #{attrib}
@#{attrib} ||= #{options[:foreign_key]}.nil? ? nil : #{options[:proxy]}.get(self.#{options[:foreign_key]}) @#{attrib} ||= #{options[:foreign_key]}.nil? ? nil : (model_proxy || #{base}).get(self.#{options[:foreign_key]})
end end
EOS EOS
end end
def create_belongs_to_setter(attrib, options) def create_belongs_to_setter(attrib, property, options)
class_eval <<-EOS, __FILE__, __LINE__ + 1 class_eval <<-EOS, __FILE__, __LINE__ + 1
def #{attrib}=(value) def #{attrib}=(value)
self.#{options[:foreign_key]} = value.nil? ? nil : value.id self.#{options[:foreign_key]} = value.nil? ? nil : value.id
@ -138,7 +125,7 @@ module CouchRest
### collection_of support methods ### collection_of support methods
def create_collection_of_property_setter(attrib, options) def create_collection_of_property_setter(attrib, property, options)
# ensure CollectionOfProxy is nil, ready to be reloaded on request # ensure CollectionOfProxy is nil, ready to be reloaded on request
class_eval <<-EOS, __FILE__, __LINE__ + 1 class_eval <<-EOS, __FILE__, __LINE__ + 1
def #{options[:foreign_key]}=(value) def #{options[:foreign_key]}=(value)
@ -148,20 +135,21 @@ module CouchRest
EOS EOS
end end
def create_collection_of_getter(attrib, options) def create_collection_of_getter(attrib, property, options)
base = options[:proxy] || options[:class_name]
class_eval <<-EOS, __FILE__, __LINE__ + 1 class_eval <<-EOS, __FILE__, __LINE__ + 1
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| (model_proxy || #{base}).get(i)}
@#{attrib} = ::CouchRest::Model::CollectionOfProxy.new(ary, find_property('#{options[:foreign_key]}'), self) @#{attrib} = ::CouchRest::CollectionOfProxy.new(ary, self, '#{options[:foreign_key]}')
end end
EOS EOS
end end
def create_collection_of_setter(attrib, options) def create_collection_of_setter(attrib, property, options)
class_eval <<-EOS, __FILE__, __LINE__ + 1 class_eval <<-EOS, __FILE__, __LINE__ + 1
def #{attrib}=(value) def #{attrib}=(value)
@#{attrib} = ::CouchRest::Model::CollectionOfProxy.new(value, find_property('#{options[:foreign_key]}'), self) @#{attrib} = ::CouchRest::CollectionOfProxy.new(value, self, '#{options[:foreign_key]}')
end end
EOS EOS
end end
@ -169,63 +157,67 @@ 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 < CastedArray class CollectionOfProxy < Array
attr_accessor :property
attr_accessor :casted_by
def initialize(array, property, parent) def initialize(array, casted_by, property)
self.property = property
self.casted_by = casted_by
(array ||= []).compact! (array ||= []).compact!
super(array, property, parent) casted_by[property.to_s] = [] # replace the original array!
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[casted_by_property.to_s] << obj.id 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[casted_by_property.to_s] << obj.id 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[casted_by_property.to_s].push obj.id 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[casted_by_property.to_s].unshift obj.id 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[casted_by_property.to_s][index] = obj.id casted_by[property.to_s][index] = obj.id
super(index, obj) super(index, obj)
end end
def pop def pop
casted_by[casted_by_property.to_s].pop casted_by[property.to_s].pop
super super
end end
def shift def shift
casted_by[casted_by_property.to_s].shift 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}##{casted_by_property.to_s} collection unless saved" if obj.new? raise "Object cannot be added to #{casted_by.class.to_s}##{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 < CouchRest::Document class Base < 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,11 +17,7 @@ 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::Dirty
include CouchRest::Model::Callbacks
def self.subclasses def self.subclasses
@subclasses ||= [] @subclasses ||= []
@ -30,7 +26,6 @@ module CouchRest
def self.inherited(subklass) def self.inherited(subklass)
super super
subklass.send(:include, CouchRest::Model::Properties) subklass.send(:include, CouchRest::Model::Properties)
subklass.class_eval <<-EOS, __FILE__, __LINE__ + 1 subklass.class_eval <<-EOS, __FILE__, __LINE__ + 1
def self.inherited(subklass) def self.inherited(subklass)
super super
@ -42,29 +37,27 @@ module CouchRest
subclasses << subklass subclasses << subklass
end end
# Accessors
attr_accessor :casted_by
# Instantiate a new CouchRest::Model::Base by preparing all properties # Instantiate a new CouchRest::Model::Base by preparing all properties
# using the provided document hash. # using the provided document hash.
# #
# 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
# #
# If a block is provided the new model will be passed into the def initialize(doc = {}, options = {})
# block so that it can be populated. doc = prepare_all_attributes(doc, options)
def initialize(attributes = {}, options = {}) # set the instances database, if provided
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
@ -82,19 +75,33 @@ module CouchRest
super super
end end
# compatbility for 1.8, it does not use respond_to_missing? ### instance methods
# thing is, when using it like this only, doing method(:find_by_view)
# will throw an error # Gets a reference to the actual document in the DB
def self.respond_to?(m, include_private = false) # Calls up to the next document if there is one,
super || respond_to_missing?(m, include_private) # Otherwise we're at the top and we return self
def base_doc
return self if base_doc?
@casted_by.base_doc
end end
# ruby 1.9 feature # Checks if we're the top document
# this allows ruby to know that the method is defined using def base_doc?
# method_missing, and as such, method(:find_by_view) will actually !@casted_by
# give a Method back, and not throw an error like in 1.8! end
def self.respond_to_missing?(m, include_private = false)
has_view?(m) || has_view?(m.to_s[/^find_(by_.+)/, 1]) ## Compatibility with ActiveSupport and older frameworks
# Hack so that CouchRest::Document, which descends from Hash,
# doesn't appear to Rails routing as a Hash of options
def is_a?(klass)
return false if klass == Hash
super
end
alias :kind_of? :is_a?
def persisted?
!new?
end end
def to_key def to_key
@ -104,26 +111,6 @@ 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,23 +5,21 @@ 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 :initialize, :only => :after define_model_callbacks \
define_model_callbacks :create, :destroy, :save, :update :create,
:destroy,
:save,
:update
end end
def valid?(*) #nodoc
_run_validation_callbacks { super }
end
end end
end end

View file

@ -5,18 +5,14 @@
module CouchRest::Model module CouchRest::Model
class CastedArray < Array class CastedArray < Array
include CouchRest::Model::CastedBy attr_accessor :casted_by
include CouchRest::Model::Dirty attr_accessor :property
attr_accessor :casted_by_property
def initialize(array, property, parent = nil) def initialize(array, property)
self.casted_by_property = property self.property = property
self.casted_by = parent unless parent.nil?
super(array) super(array)
end end
# Adding new entries
def << obj def << obj
super(instantiate_and_cast(obj)) super(instantiate_and_cast(obj))
end end
@ -25,57 +21,17 @@ module CouchRest::Model
super(instantiate_and_cast(obj)) super(instantiate_and_cast(obj))
end end
def unshift(obj)
super(instantiate_and_cast(obj))
end
def []= index, obj def []= index, obj
value = instantiate_and_cast(obj, false) super(index, instantiate_and_cast(obj))
couchrest_parent_will_change! if use_dirty? && value != self[index]
super(index, value)
end
def pop
couchrest_parent_will_change! if use_dirty? && self.length > 0
super
end
def shift
couchrest_parent_will_change! if use_dirty? && self.length > 0
super
end
def clear
couchrest_parent_will_change! if use_dirty? && self.length > 0
super
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 end
protected protected
def instantiate_and_cast(obj, change = true) def instantiate_and_cast(obj)
property = casted_by_property if self.casted_by && self.property && obj.class != self.property.type_class
couchrest_parent_will_change! if change && use_dirty? self.property.cast_value(self.casted_by, obj)
if casted_by && property && obj.class != property.type_class
property.cast_value(casted_by, obj)
else else
obj.casted_by = casted_by if obj.respond_to?(:casted_by) obj.casted_by = self.casted_by if obj.respond_to?(:casted_by)
obj.casted_by_property = casted_by_property if obj.respond_to?(:casted_by_property)
obj obj
end end
end end

View file

@ -1,33 +0,0 @@
module CouchRest::Model
module CastedBy
extend ActiveSupport::Concern
included do
self.send(:attr_accessor, :casted_by)
self.send(:attr_accessor, :casted_by_property)
end
# Gets a reference to the actual document in the DB
# Calls up to the next document if there is one,
# Otherwise we're at the top and we return self
def base_doc
return self if base_doc?
casted_by ? casted_by.base_doc : nil
end
# Checks if we're the top document
def base_doc?
!casted_by
end
# Provide the property this casted model instance has been
# used by. If it has not been set, search through the
# casted_by objects properties to try and find it.
#def casted_by_property
# return nil unless casted_by
# attrs = casted_by.attributes
# @casted_by_property ||= casted_by.properties.detect{ |k| attrs[k.to_s] === self }
#end
end
end

View file

@ -1,84 +0,0 @@
#
# Wrapper around Hash so that the casted_by attribute is set.
module CouchRest::Model
class CastedHash < Hash
include CouchRest::Model::CastedBy
include CouchRest::Model::Dirty
attr_accessor :casted_by_property
def self.[](hash, property, parent = nil)
obj = super(hash)
obj.casted_by_property = property
obj.casted_by = parent unless parent.nil?
obj
end
# needed for dirty
def attributes
self
end
def []= key, obj
couchrest_attribute_will_change!(key) if use_dirty? && obj != self[key]
super(key, obj)
end
def delete(key)
couchrest_attribute_will_change!(key) if use_dirty? && include?(key)
super(key)
end
def merge!(other_hash)
if use_dirty? && other_hash && other_hash.kind_of?(Hash)
other_hash.keys.each do |key|
if self[key] != other_hash[key] || !include?(key)
couchrest_attribute_will_change!(key)
end
end
end
super(other_hash)
end
def replace(other_hash)
if use_dirty? && other_hash && other_hash.kind_of?(Hash)
# new keys and changed keys
other_hash.keys.each do |key|
if self[key] != other_hash[key] || !include?(key)
couchrest_attribute_will_change!(key)
end
end
# old keys
old_keys = self.keys.reject { |key| other_hash.include?(key) }
old_keys.each { |key| couchrest_attribute_will_change!(key) }
end
super(other_hash)
end
def clear
self.keys.each { |key| couchrest_attribute_will_change!(key) } if use_dirty?
super
end
def delete_if
if use_dirty? && block_given?
self.keys.each do |key|
couchrest_attribute_will_change!(key) if yield key, self[key]
end
end
super
end
# ruby 1.9
def keep_if
if use_dirty? && block_given?
self.keys.each do |key|
couchrest_attribute_will_change!(key) if !yield key, self[key]
end
end
super
end
end
end

View file

@ -1,43 +1,43 @@
module CouchRest::Model module CouchRest::Model
module Embeddable module CastedModel
extend ActiveSupport::Concern
# Include Attributes early to ensure super() will work extend ActiveSupport::Concern
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 attr_accessor :casted_by
include CouchRest::Model::CastedBy
include CouchRest::Model::Dirty
include CouchRest::Model::Callbacks
class_eval do
# Override CastedBy's base_doc?
def base_doc?
false # Can never be base doc!
end end
end def initialize(keys = {})
end raise StandardError unless self.is_a? Hash
prepare_all_attributes(keys)
# Initialize a new Casted Model. Accepts the same
# options as CouchRest::Model::Base for preparing and initializing
# attributes.
def initialize(keys = {}, options = {})
super() super()
prepare_all_attributes(keys, options) end
run_callbacks(:initialize) { self }
def []= key, value
super(key.to_s, value)
end
def [] key
super(key.to_s)
end
# Gets a reference to the top level extended
# document that a model is saved inside of
def base_doc
return nil unless @casted_by
@casted_by.base_doc
end end
# False if the casted model has already # False if the casted model has already
# been saved in the containing document # been saved in the containing document
def new? def new?
casted_by.nil? ? true : casted_by.new? @casted_by.nil? ? true : @casted_by.new?
end end
alias :new_record? :new? alias :new_record? :new?
@ -64,15 +64,5 @@ module CouchRest::Model
end end
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

@ -88,13 +88,6 @@ 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

@ -1,11 +1,5 @@
module CouchRest module CouchRest
module Model module Model
# Warning! The Collection module is seriously depricated.
# Use the new Design Views instead, as this code copies many other parts
# of CouchRest Model.
#
# Expect this to be removed soon.
#
module Collection module Collection
def self.included(base) def self.included(base)
@ -137,9 +131,6 @@ module CouchRest
else else
@view_name = "#{design_doc}/#{view_name}" @view_name = "#{design_doc}/#{view_name}"
end end
# Save the design doc, ready for use
@container_class.save_design_doc(@database)
end end
# See Collection.paginate # See Collection.paginate
@ -244,7 +235,6 @@ 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

@ -10,28 +10,10 @@ module CouchRest
included do included do
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 :environment
add_config :connection
add_config :connection_config_file
configure do |config| configure do |config|
config.model_type_key = 'type' # was 'couchrest-type' config.model_type_key = 'couchrest-type' # 'model'?
config.mass_assign_any_attribute = false config.mass_assign_any_attribute = false
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
@ -65,3 +47,5 @@ module CouchRest
end end
end end
end end

View file

@ -1,70 +0,0 @@
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

@ -1,66 +0,0 @@
module CouchRest
module Model
module CoreExtensions
module TimeParsing
if RUBY_VERSION < "1.9.0"
# Overrwrite Ruby's standard new method to provide compatible support
# of 1.9.2's Time.new method.
#
# Only supports syntax like:
#
# Time.new(2011, 4, 1, 18, 50, 32, "+02:00")
# # or
# Time.new(2011, 4, 1, 18, 50, 32)
#
def new(*args)
return super() if (args.empty?)
zone = args.delete_at(6)
time = mktime(*args)
if zone =~ /([\+|\-]?)(\d{2}):?(\d{2})/
tz_difference = ("#{$1 == '-' ? '+' : '-'}#{$2}".to_i * 3600) + ($3.to_i * 60)
time + tz_difference + zone_offset(time.zone)
else
time
end
end
end
# Attemtps to parse a time string in ISO8601 format.
# If no match is found, the standard time parse will be used.
#
# Times, unless provided with a time zone, are assumed to be in
# UTC.
#
def parse_iso8601(string)
if (string =~ /(\d{4})[\-|\/](\d{2})[\-|\/](\d{2})[T|\s](\d{2}):(\d{2}):(\d{2})(Z| ?([\+|\s|\-])?(\d{2}):?(\d{2}))?/)
# $1 = year
# $2 = month
# $3 = day
# $4 = hours
# $5 = minutes
# $6 = seconds
# $7 = UTC or Timezone
# $8 = time zone direction
# $9 = tz difference hours
# $10 = tz difference minutes
if (!$7.to_s.empty? && $7 != 'Z')
new($1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i, "#{$8 == '-' ? '-' : '+'}#{$9}:#{$10}")
else
utc($1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i)
end
else
parse(string)
end
end
end
end
end
end
Time.class_eval do
extend CouchRest::Model::CoreExtensions::TimeParsing
end

View file

@ -7,11 +7,13 @@ module CouchRest
module ClassMethods module ClassMethods
def design_doc def design_doc
@design_doc ||= if auto_update_design_doc @design_doc ||= Design.new(default_design_doc)
::CouchRest::Design.new(default_design_doc)
else
stored_design_doc || ::CouchRest::Design.new(default_design_doc)
end end
# Use when something has been changed, like a view, so that on the next request
# the design docs will be updated (if changed!)
def req_design_doc_refresh
@design_doc_fresh = { }
end end
def design_doc_id def design_doc_id
@ -22,89 +24,6 @@ module CouchRest
self.to_s self.to_s
end end
def design_doc_uri(db = database)
"#{db.root}/#{design_doc_id}"
end
# Retreive the latest version of the design document directly
# from the database. This is never cached and will return nil if
# the design is not present.
#
# Use this method if you'd like to compare revisions [_rev] which
# is not stored in the normal design doc.
def stored_design_doc(db = database)
db.get(design_doc_id)
rescue RestClient::ResourceNotFound
nil
end
# Save the design doc onto a target database in a thread-safe way,
# not modifying the model's design_doc
#
# See also save_design_doc! to always save the design doc even if there
# are no changes.
def save_design_doc(db = database, force = false)
update_design_doc(db, force)
end
# Force the update of the model's design_doc even if it hasn't changed.
def save_design_doc!(db = database)
save_design_doc(db, true)
end
private
def design_doc_cache
Thread.current[:couchrest_design_cache] ||= {}
end
def design_doc_cache_checksum(db)
design_doc_cache[design_doc_uri(db)]
end
def set_design_doc_cache_checksum(db, checksum)
design_doc_cache[design_doc_uri(db)] = checksum
end
# Writes out a design_doc to a given database if forced
# or the stored checksum is not the same as the current
# generated checksum.
#
# Returns the original design_doc provided, but does
# not update it with the revision.
def update_design_doc(db, force = false)
return design_doc unless force || auto_update_design_doc
# Grab the design doc's checksum
checksum = design_doc.checksum!
# If auto updates enabled, check checksum cache
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
saved = stored_design_doc(db)
if saved
if force || saved['couchrest-hash'] != checksum
saved.merge!(design_doc)
db.save_doc(saved)
@design_doc = saved # update memo to point to the document we actually saved
end
else
design_doc.delete('_rev') # This is a new document and so doesn't have a revision yet
db.save_doc(design_doc)
end
rescue RestClient::Conflict
# if we get a conflict retry the operation...
raise if retries < 1
retries -= 1
retry
end
# Ensure checksum cached for next attempt if using auto updates
set_design_doc_cache_checksum(db, checksum) if auto_update_design_doc
design_doc
end
def default_design_doc def default_design_doc
{ {
"_id" => design_doc_id, "_id" => design_doc_id,
@ -121,6 +40,82 @@ module CouchRest
} }
end end
# DEPRECATED
# use stored_design_doc to retrieve the current design doc
def all_design_doc_versions(db = database)
db.documents :startkey => "_design/#{self.to_s}",
:endkey => "_design/#{self.to_s}-\u9999"
end
# Retreive the latest version of the design document directly
# from the database.
def stored_design_doc(db = database)
db.get(design_doc_id) rescue nil
end
alias :model_design_doc :stored_design_doc
def refresh_design_doc(db = database)
raise "Database missing for design document refresh" if db.nil?
unless design_doc_fresh(db)
save_design_doc(db)
design_doc_fresh(db, true)
end
end
# Save the design doc onto a target database in a thread-safe way,
# not modifying the model's design_doc
#
# See also save_design_doc! to always save the design doc even if there
# are no changes.
def save_design_doc(db = database, force = false)
update_design_doc(Design.new(design_doc), db, force)
end
# Force the update of the model's design_doc even if it hasn't changed.
def save_design_doc!(db = database)
save_design_doc(db, true)
end
protected
def design_doc_fresh(db, fresh = nil)
@design_doc_fresh ||= {}
if fresh.nil?
@design_doc_fresh[db.uri] || false
else
@design_doc_fresh[db.uri] = fresh
end
end
# Writes out a design_doc to a given database, returning the
# updated design doc
def update_design_doc(design_doc, db, force = false)
saved = stored_design_doc(db)
if saved
changes = force
design_doc['views'].each do |name, view|
if !compare_views(saved['views'][name], view)
changes = true
saved['views'][name] = view
end
end
if changes
db.save_doc(saved)
end
design_doc
else
design_doc.database = db
design_doc.save
design_doc
end
end
# Return true if the two views match
def compare_views(orig, repl)
return false if orig.nil? or repl.nil?
(orig['map'].to_s.strip == repl['map'].to_s.strip) && (orig['reduce'].to_s.strip == repl['reduce'].to_s.strip)
end
end # module ClassMethods end # module ClassMethods
end end

View file

@ -28,6 +28,8 @@ module CouchRest
mapper.create_view_method(:all) mapper.create_view_method(:all)
mapper.instance_eval(&block) if block_given? mapper.instance_eval(&block) if block_given?
req_design_doc_refresh
end end
# Override the default page pagination value: # Override the default page pagination value:
@ -58,25 +60,13 @@ module CouchRest
self.model = model self.model = model
end end
# Generate a method that will provide a new View instance when # Define a view and generate a method that will provide a new
# requested. This will also define the view in CouchDB unless # View instance when requested.
# auto_update_design_doc is disabled.
def view(name, opts = {}) def view(name, opts = {})
View.create(model, name, opts) if model.auto_update_design_doc View.create(model, name, opts)
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

@ -25,7 +25,7 @@ module CouchRest
self.owner = parent self.owner = parent
self.name = name.to_s self.name = name.to_s
# Default options: # Default options:
self.query = { } self.query = { :reduce => false }
elsif parent.is_a?(self.class) elsif parent.is_a?(self.class)
self.model = (new_query.delete(:proxy) || parent.model) self.model = (new_query.delete(:proxy) || parent.model)
self.owner = parent.owner self.owner = parent.owner
@ -90,13 +90,6 @@ module CouchRest
result ? all.last : limit(1).descending.all.last result ? all.last : limit(1).descending.all.last
end end
# Return the number of documents in the currently defined result set.
# Use <tt>#count</tt> for the total number of documents regardless
# of the current limit defined.
def length
docs.length
end
# Perform a count operation based on the current view. If the view # Perform a count operation based on the current view. If the view
# can be reduced, the reduce will be performed and return the first # can be reduced, the reduce will be performed and return the first
# value. This is okay for most simple queries, but may provide # value. This is okay for most simple queries, but may provide
@ -113,7 +106,7 @@ module CouchRest
def count def count
raise "View#count cannot be used with group options" if query[:group] raise "View#count cannot be used with group options" if query[:group]
if can_reduce? if can_reduce?
row = reduce.skip(0).limit(1).rows.first row = reduce.rows.first
row.nil? ? 0 : row.value row.nil? ? 0 : row.value
else else
limit(0).total_rows limit(0).total_rows
@ -146,6 +139,12 @@ module CouchRest
execute['total_rows'] execute['total_rows']
end end
# Convenience wrapper around the rows result set. This will provide
# and array of keys.
def keys
rows.map{|r| r.key}
end
# Convenience wrapper to provide all the values from the route # Convenience wrapper to provide all the values from the route
# set without having to go through +rows+. # set without having to go through +rows+.
def values def values
@ -182,7 +181,7 @@ module CouchRest
# #
# Cannot be used when the +#startkey+ or +#endkey+ have been set. # Cannot be used when the +#startkey+ or +#endkey+ have been set.
def key(value) def key(value)
raise "View#key cannot be used when startkey or endkey have been set" unless query[:keys].nil? && query[:startkey].nil? && query[:endkey].nil? raise "View#key cannot be used when startkey or endkey have been set" unless query[:startkey].nil? && query[:endkey].nil?
update_query(:key => value) update_query(:key => value)
end end
@ -194,7 +193,7 @@ module CouchRest
# #
# Cannot be used if the key has been set. # Cannot be used if the key has been set.
def startkey(value) def startkey(value)
raise "View#startkey cannot be used when key has been set" unless query[:key].nil? && query[:keys].nil? raise "View#startkey cannot be used when key has been set" unless query[:key].nil?
update_query(:startkey => value) update_query(:startkey => value)
end end
@ -211,7 +210,7 @@ module CouchRest
# See the +#startkey+ method for more details and the +#inclusive_end+ # See the +#startkey+ method for more details and the +#inclusive_end+
# option. # option.
def endkey(value) def endkey(value)
raise "View#endkey cannot be used when key has been set" unless query[:key].nil? && query[:keys].nil? raise "View#endkey cannot be used when key has been set" unless query[:key].nil?
update_query(:endkey => value) update_query(:endkey => value)
end end
@ -222,36 +221,12 @@ module CouchRest
update_query(:endkey_docid => value.is_a?(String) ? value : value.id) update_query(:endkey_docid => value.is_a?(String) ? value : value.id)
end end
# Keys is a special CouchDB option that will cause the view request to be POSTed
# including an array of keys. Only documents with the matching keys will be
# returned. This is much faster than sending multiple requests for a set
# non-consecutive documents.
#
# If no values are provided, this method will act as a wrapper around
# the rows result set, providing an array of keys.
def keys(*keys)
if keys.empty?
rows.map{|r| r.key}
else
raise "View#keys cannot by used when key or startkey/endkey have been set" unless query[:key].nil? && query[:startkey].nil? && query[:endkey].nil?
update_query(:keys => keys.first)
end
end
# The results should be provided in descending order.
# The results should be provided in descending order. If the startkey or
# endkey query options have already been seen set, calling this method
# will automatically swap the options around. If you don't want this,
# simply set descending before any other option.
# #
# Descending is false by default, and this method cannot # Descending is false by default, this method will enable it and cannot
# be undone once used, it has no inverse option. # be undone.
def descending def descending
if query[:startkey] || query[:endkey]
query[:startkey], query[:endkey] = query[:endkey], query[:startkey]
elsif query[:startkey_docid] || query[:endkey_docid]
query[:startkey_docid], query[:endkey_docid] = query[:endkey_docid], query[:startkey_docid]
end
update_query(:descending => true) update_query(:descending => true)
end end
@ -366,6 +341,8 @@ module CouchRest
(offset_value / limit_value) + 1 (offset_value / limit_value) + 1
end end
protected protected
def include_docs! def include_docs!
@ -398,22 +375,30 @@ module CouchRest
def execute def execute
return self.result if result return self.result if result
raise "Database must be defined in model or view!" if use_database.nil? raise "Database must be defined in model or view!" if use_database.nil?
retryable = true
# Remove the reduce value if its not needed to prevent CouchDB errors # Remove the reduce value if its not needed
query.delete(:reduce) unless can_reduce? query.delete(:reduce) unless can_reduce?
begin
model.save_design_doc(use_database)
self.result = model.design_doc.view_on(use_database, name, query.reject{|k,v| v.nil?}) self.result = model.design_doc.view_on(use_database, name, query.reject{|k,v| v.nil?})
rescue RestClient::ResourceNotFound => e
if retryable
model.save_design_doc(use_database)
retryable = false
retry
else
raise e
end
end
end end
# Class Methods # Class Methods
class << self class << self
# Simplified view creation. A new view will be added to the # Simplified view creation. A new view will be added to the
# provided model's design document using the name and options. # provided model's design document using the name and options.
# #
# If the view name starts with "by_" and +:by+ is not provided in # If the view name starts with "by_" and +:by+ is not provided in
# the options, the new view's map method will be interpreted and # the options, the new view's map method will be interpretted and
# generated automatically. For example: # generated automatically. For example:
# #
# View.create(Meeting, "by_date_and_name") # View.create(Meeting, "by_date_and_name")
@ -427,16 +412,6 @@ module CouchRest
# The view name is the same, but three keys would be used in the # The view name is the same, but three keys would be used in the
# subsecuent index. # subsecuent index.
# #
# By default, a check is made on each of the view's keys to ensure they
# do not contain a nil value ('null' in javascript). This is probably what
# you want in most cases but sometimes in can be useful to create an
# index where nil is permited. Set the <tt>:allow_nil</tt> option to true to
# remove this check.
#
# Conversely, keys are not checked to see if they are empty or blank. If you'd
# like to enable this, set the <tt>:allow_blank</tt> option to false. The default
# is true, empty strings are permited in the indexes.
#
def create(model, name, opts = {}) def create(model, name, opts = {})
unless opts[:map] unless opts[:map]
@ -446,14 +421,12 @@ module CouchRest
raise "View cannot be created without recognised name, :map or :by options" if opts[:by].nil? raise "View cannot be created without recognised name, :map or :by options" if opts[:by].nil?
opts[:allow_blank] = opts[:allow_blank].nil? ? true : opts[:allow_blank]
opts[:guards] ||= [] opts[:guards] ||= []
opts[:guards].push "(doc['#{model.model_type_key}'] == '#{model.to_s}')" opts[:guards].push "(doc['#{model.model_type_key}'] == '#{model.to_s}')"
keys = opts[:by].map{|o| "doc['#{o}']"} keys = opts[:by].map{|o| "doc['#{o}']"}
emit = keys.length == 1 ? keys.first : "[#{keys.join(', ')}]" emit = keys.length == 1 ? keys.first : "[#{keys.join(', ')}]"
opts[:guards] += keys.map{|k| "(#{k} != null)"} unless opts[:allow_nil] opts[:guards] += keys.map{|k| "(#{k} != null)"}
opts[:guards] += keys.map{|k| "(#{k} != '')"} unless opts[:allow_blank]
opts[:map] = <<-EOF opts[:map] = <<-EOF
function(doc) { function(doc) {
if (#{opts[:guards].join(' && ')}) { if (#{opts[:guards].join(' && ')}) {

View file

@ -1,39 +0,0 @@
# encoding: utf-8
I18n.load_path << File.join(
File.dirname(__FILE__), "validations", "locale", "en.yml"
)
module CouchRest
module Model
# This applies to both Model::Base and Model::CastedModel
module Dirty
extend ActiveSupport::Concern
include ActiveModel::Dirty
included do
# internal dirty setting - overrides global setting.
# this is used to temporarily disable dirty tracking when setting
# attributes directly, for performance reasons.
self.send(:attr_accessor, :disable_dirty)
end
def use_dirty?
doc = base_doc
doc && !doc.disable_dirty
end
def couchrest_attribute_will_change!(attr)
return if attr.nil? || !use_dirty?
attribute_will_change!(attr)
couchrest_parent_will_change!
end
def couchrest_parent_will_change!
casted_by.couchrest_attribute_will_change!(casted_by_property.name) if casted_by_property
end
end
end
end

View file

@ -1,7 +1,10 @@
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
@ -83,12 +86,9 @@ 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 CouchRest::Model::DocumentNotFound if id.blank? raise "Missing or empty document ID" if id.to_s.empty?
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

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

View file

@ -1,7 +1,6 @@
module CouchRest module CouchRest
module Model module Model
module ExtendedAttachments module ExtendedAttachments
extend ActiveSupport::Concern
# Add a file attachment to the current document. Expects # Add a file attachment to the current document. Expects
# :file and :name to be included in the arguments. # :file and :name to be included in the arguments.
@ -36,11 +35,8 @@ module CouchRest
# deletes a file attachment from the current doc # deletes a file attachment from the current doc
def delete_attachment(attachment_name) def delete_attachment(attachment_name)
return unless attachments return unless attachments
if attachments.include?(attachment_name)
attribute_will_change!("_attachments")
attachments.delete attachment_name attachments.delete attachment_name
end end
end
# returns true if attachment_name exists # returns true if attachment_name exists
def has_attachment?(attachment_name) def has_attachment?(attachment_name)
@ -70,8 +66,6 @@ module CouchRest
def set_attachment_attr(args) def set_attachment_attr(args)
content_type = args[:content_type] ? args[:content_type] : get_mime_type(args[:file].path) content_type = args[:content_type] ? args[:content_type] : get_mime_type(args[:file].path)
content_type ||= (get_mime_type(args[:name]) || 'text/plain') content_type ||= (get_mime_type(args[:name]) || 'text/plain')
attribute_will_change!("_attachments")
attachments[args[:name]] = { attachments[args[:name]] = {
'content_type' => content_type, 'content_type' => content_type,
'data' => args[:file].read 'data' => args[:file].read

View file

@ -12,32 +12,26 @@ module CouchRest
_run_save_callbacks do _run_save_callbacks do
set_unique_id if new? && self.respond_to?(:set_unique_id) set_unique_id if new? && self.respond_to?(:set_unique_id)
result = database.save_doc(self) result = database.save_doc(self)
ret = (result["ok"] == true) ? self : false (result["ok"] == true) ? self : false
@changed_attributes.clear if ret && @changed_attributes
ret
end end
end end
end end
# 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!(options = {}) def create!
self.class.fail_validate!(self) unless self.create(options) self.class.fail_validate!(self) unless self.create
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 "Cannot save a destroyed document!" if destroyed? raise "Calling #{self.class.name}#update on document that has not been created!" if self.new?
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?
_run_update_callbacks do _run_update_callbacks do
_run_save_callbacks do _run_save_callbacks do
result = database.save_doc(self) result = database.save_doc(self)
ret = result["ok"] == true result["ok"] == true
@changed_attributes.clear if ret && @changed_attributes
ret
end end
end end
end end
@ -55,25 +49,19 @@ 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']
@_destroyed = true self.delete('_rev')
self.freeze self.delete('_id')
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"
@ -92,10 +80,11 @@ module CouchRest
# #
# Returns self. # Returns self.
def reload def reload
prepare_all_attributes(database.get(id), :directly_set_attributes => true) merge!(self.class.get(id))
self self
end end
protected protected
def perform_validations(options = {}) def perform_validations(options = {})
@ -111,25 +100,22 @@ module CouchRest
module ClassMethods module ClassMethods
# Creates a new instance, bypassing attribute protection and # Creates a new instance, bypassing attribute protection
# 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 = {}, options = {}, &block) def build_from_database(doc = {})
src = doc[model_type_key] base = (doc[model_type_key].blank? || doc[model_type_key] == self.to_s) ? self : doc[model_type_key].constantize
base = (src.blank? || src == self.to_s) ? self : src.constantize base.new(doc, :directly_set_attributes => true)
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 = {}, &block) def create(attributes = {})
instance = new(attributes, &block) instance = new(attributes)
instance.create instance.create
instance instance
end end
@ -138,8 +124,8 @@ module CouchRest
# #
# ==== Returns # ==== Returns
# returns the reloaded document or raises an exception # returns the reloaded document or raises an exception
def create!(attributes = {}, &block) def create!(attributes = {})
instance = new(attributes, &block) instance = new(attributes)
instance.create! instance.create!
instance instance
end end
@ -152,7 +138,7 @@ module CouchRest
# must be globally unique across all document types which share a # must be globally unique across all document types which share a
# database, so if you'd like to scope uniqueness to this class, you # database, so if you'd like to scope uniqueness to this class, you
# should use the class name as part of the unique id. # should use the class name as part of the unique id.
def unique_id(method = nil, &block) def unique_id method = nil, &block
if method if method
define_method :set_unique_id do define_method :set_unique_id do
self['_id'] ||= self.send(method) self['_id'] ||= self.send(method)

View file

@ -5,17 +5,17 @@ module CouchRest
extend ActiveSupport::Concern extend ActiveSupport::Concern
included do included do
class_attribute(:properties) unless self.respond_to?(:properties) extlib_inheritable_accessor(:properties) unless self.respond_to?(:properties)
class_attribute(:properties_by_name) unless self.respond_to?(:properties_by_name)
self.properties ||= [] self.properties ||= []
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
# Provide an attribute hash ready to be sent to CouchDB but with # Returns the Class properties
# all the nil attributes removed. #
def as_couch_json # ==== Returns
super.delete_if{|k,v| v.nil?} # Array:: the list of properties for model's class
def properties
self.class.properties
end end
# Returns the Class properties with their values # Returns the Class properties with their values
@ -37,12 +37,10 @@ module CouchRest
end end
# Store a casted value in the current instance of an attribute defined # Store a casted value in the current instance of an attribute defined
# with a property and update dirty status # with a property.
def write_attribute(property, value) def write_attribute(property, value)
prop = find_property!(property) prop = find_property!(property)
value = prop.is_a?(String) ? value : prop.cast(self, value) self[prop.to_s] = prop.is_a?(String) ? value : prop.cast(self, value)
couchrest_attribute_will_change!(prop.name) if use_dirty? && self[prop.name] != value
self[prop.name] = value
end end
# Takes a hash as argument, and applies the values by using writer methods # Takes a hash as argument, and applies the values by using writer methods
@ -56,61 +54,45 @@ module CouchRest
end end
alias :attributes= :update_attributes_without_saving alias :attributes= :update_attributes_without_saving
# 'attributes' needed for Dirty
alias :attributes :properties_with_values
def set_attributes(hash)
attrs = remove_protected_attributes(hash)
directly_set_attributes(attrs)
end
protected
def find_property(property)
property.is_a?(Property) ? property : self.class.properties_by_name[property.to_s]
end
private
# The following methods should be accessable by the Model::Base Class, but not by anything else! # The following methods should be accessable by the Model::Base Class, but not by anything else!
def apply_all_property_defaults def apply_all_property_defaults
return if self.respond_to?(:new?) && (new? == false) return if self.respond_to?(:new?) && (new? == false)
# TODO: cache the default object # TODO: cache the default object
# Never mark default options as dirty!
dirty, self.disable_dirty = self.disable_dirty, true
self.class.properties.each do |property| self.class.properties.each do |property|
write_attribute(property, property.default_value) write_attribute(property, property.default_value)
end end
self.disable_dirty = dirty
end end
def prepare_all_attributes(attrs = {}, options = {}) def prepare_all_attributes(doc = {}, options = {})
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(attrs) directly_set_read_only_attributes(doc)
directly_set_attributes(attrs, true)
else else
attrs = remove_protected_attributes(attrs) doc = remove_protected_attributes(doc)
directly_set_attributes(attrs)
end end
self.disable_dirty = false directly_set_attributes(doc) unless doc.nil?
self
end end
def find_property!(property) def find_property!(property)
prop = find_property(property) prop = property.is_a?(Property) ? property : self.class.properties.detect {|p| p.to_s == property.to_s}
raise ArgumentError, "Missing property definition for #{property.to_s}" if prop.nil? raise ArgumentError, "Missing property definition for #{property.to_s}" if prop.nil?
prop prop
end end
# 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, mass_assign = false) def directly_set_attributes(hash)
return if hash.nil? hash.reject do |attribute_name, attribute_value|
hash.reject do |key, value| if self.respond_to?("#{attribute_name}=")
if self.respond_to?("#{key}=") self.send("#{attribute_name}=", attribute_value)
self.send("#{key}=", value) true
elsif mass_assign || mass_assign_any_attribute elsif mass_assign_any_attribute # config option
self[key] = value self[attribute_name] = attribute_value
true
else
false
end end
end end
end end
@ -125,12 +107,15 @@ module CouchRest
end end
end end
def set_attributes(hash)
attrs = remove_protected_attributes(hash)
directly_set_attributes(attrs)
end
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 && CouchRest::Model::Base >= self
opts = { } opts = { }
type = options.shift type = options.shift
if type.class != Hash if type.class != Hash
@ -146,11 +131,10 @@ module CouchRest
end end
# Automatically set <tt>updated_at</tt> and <tt>created_at</tt> fields # Automatically set <tt>updated_at</tt> and <tt>created_at</tt> fields
# on the document whenever saving occurs. # on the document whenever saving occurs. CouchRest uses a pretty
# # decent time format by default. See Time#to_json
# These properties are casted as Time objects, so they should always
# 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)
@ -158,6 +142,7 @@ 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
@ -168,8 +153,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 do type = Class.new(Hash) do
include Embeddable include CastedModel
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 }
@ -185,38 +170,47 @@ module CouchRest
validates_casted_model property.name validates_casted_model property.name
end end
properties << property properties << property
properties_by_name[property.to_s] = property
property property
end end
# 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)
define_method(property.name) do # meth = property.name
read_attribute(property.name) class_eval <<-EOS, __FILE__, __LINE__ + 1
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)
define_method("#{property.name}?") do class_eval <<-EOS, __FILE__, __LINE__
value = read_attribute(property.name) def #{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
alias_method(property.alias, property.name.to_sym) class_eval <<-EOS, __FILE__, __LINE__ + 1
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)
name = property.name property_name = property.name
class_eval <<-EOS
define_method("#{name}=") do |value| def #{property_name}=(value)
write_attribute(name, value) write_attribute('#{property_name}', value)
end end
EOS
if property.alias if property.alias
alias_method "#{property.alias}=", "#{name}=" class_eval <<-EOS
alias #{property.alias.to_sym}= #{property_name.to_sym}=
EOS
end end
end end

View file

@ -27,24 +27,28 @@ 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 params hash where key is index # Assume provided as a Hash where key is index!
value = parameter_hash_to_array(value) data = 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) value = type_class != String ? CastedArray.new(arr, self) : arr
elsif (type == Object || type == Hash) && (value.is_a?(Hash)) value.casted_by = parent if value.respond_to?(:casted_by)
# allow casted_by calls to be passed up chain by wrapping in CastedHash
CastedHash[value, self, parent]
elsif !value.nil? elsif !value.nil?
cast_value(parent, value) value = cast_value(parent, value)
end end
value
end end
# Cast an individual value # Cast an individual value, not an array
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
@ -59,31 +63,10 @@ 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 value
end end

View file

@ -4,61 +4,31 @@ module CouchRest
module Proxyable module Proxyable
extend ActiveSupport::Concern extend ActiveSupport::Concern
def proxy_database included do
raise StandardError, "Please set the #proxy_database_method" if self.class.proxy_database_method.nil? attr_accessor :model_proxy
@proxy_database ||= self.class.prepare_database(self.send(self.class.proxy_database_method))
end 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(model_name, options = {})
db_method = options[:database_method] || "proxy_database" db_method = options[:database_method] || "proxy_database"
options[:class_name] ||= assoc_name.to_s.singularize.camelize options[:class_name] ||= model_name.to_s.singularize.camelize
class_eval <<-EOS, __FILE__, __LINE__ + 1 class_eval <<-EOS, __FILE__, __LINE__ + 1
def #{assoc_name} def #{model_name}
@#{assoc_name} ||= CouchRest::Model::Proxyable::ModelProxy.new(::#{options[:class_name]}, self, self.class.to_s.underscore, #{db_method}) unless respond_to?('#{db_method}')
raise "Missing ##{db_method} method for proxy"
end
@#{model_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)
self.proxy_owner_method = model_name
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
# for each Class using the base.
# Perhaps there is a shorter way of writing this.
def proxy_owner_method=(name); @proxy_owner_method = name; 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
@ -73,12 +43,13 @@ module CouchRest
end end
# Base # Base
def new(attrs = {}, options = {}, &block)
proxy_block_update(:new, attrs, options, &block) def new(*args)
proxy_update(model.new(*args))
end end
def build_from_database(attrs = {}, options = {}, &block) def build_from_database(doc = {})
proxy_block_update(:build_from_database, attrs, options, &block) proxy_update(model.build_from_database(doc))
end end
def method_missing(m, *args, &block) def method_missing(m, *args, &block)
@ -142,10 +113,15 @@ module CouchRest
end end
# DesignDoc # DesignDoc
def design_doc def design_doc
@model.design_doc @model.design_doc
end end
def refresh_design_doc(db = nil)
@model.refresh_design_doc(db || @database)
end
def save_design_doc(db = nil) def save_design_doc(db = nil)
@model.save_design_doc(db || @database) @model.save_design_doc(db || @database)
end end
@ -156,10 +132,10 @@ module CouchRest
# Update the document's proxy details, specifically, the fields that # Update the document's proxy details, specifically, the fields that
# link back to the original document. # link back to the original document.
def proxy_update(doc) def proxy_update(doc)
if doc && doc.is_a?(model) if doc
doc.database = @database doc.database = @database if doc.respond_to?(:database=)
doc.model_proxy = self doc.model_proxy = self if doc.respond_to?(:model_proxy=)
doc.send("#{owner_name}=", owner) doc.send("#{owner_name}=", owner) if doc.respond_to?("#{owner_name}=")
end end
doc doc
end end
@ -170,13 +146,6 @@ 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,19 @@
module CouchRest
class Database
alias :delete_orig! :delete!
def delete!
clear_model_fresh_cache
delete_orig!
end
# If the database is deleted, ensure that the design docs will be refreshed.
def clear_model_fresh_cache
::CouchRest::Model::Base.subclasses.each{|klass| klass.req_design_doc_refresh if klass.respond_to?(:req_design_doc_refresh)}
end
end
end

View file

@ -1,13 +0,0 @@
#
# 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

@ -1,33 +0,0 @@
CouchRest::Design.class_eval do
# Calculate and update the checksum of the Design document.
# Used for ensuring the latest version has been sent to the database.
#
# This will generate an flatterned, ordered array of all the elements of the
# design document, convert to string then generate an MD5 Hash. This should
# result in a consisitent Hash accross all platforms.
#
def checksum!
# create a copy of basic elements
base = self.dup
base.delete('_id')
base.delete('_rev')
base.delete('couchrest-hash')
result = nil
flatten =
lambda {|r|
(recurse = lambda {|v|
if v.is_a?(Hash) || v.is_a?(CouchRest::Document)
v.to_a.map{|v| recurse.call(v)}.flatten
elsif v.is_a?(Array)
v.flatten.map{|v| recurse.call(v)}
else
v.to_s
end
}).call(r)
}
self['couchrest-hash'] = Digest::MD5.hexdigest(flatten.call(base).sort.join(''))
end
end

View file

@ -1,3 +1,26 @@
class Time
# returns a local time value much faster than Time.parse
def self.mktime_with_offset(string)
string =~ /(\d{4})[\-|\/](\d{2})[\-|\/](\d{2})[T|\s](\d{2}):(\d{2}):(\d{2})(([\+|\s|\-])*(\d{2}):?(\d{2}))?/
# $1 = year
# $2 = month
# $3 = day
# $4 = hours
# $5 = minutes
# $6 = seconds
# $8 = time zone direction
# $9 = tz difference
# utc time with wrong TZ info:
time = mktime($1, RFC2822_MONTH_NAME[$2.to_i - 1], $3, $4, $5, $6)
if ($7)
tz_difference = ("#{$8 == '-' ? '+' : '-'}#{$9}".to_i * 3600)
time + tz_difference + zone_offset(time.zone)
else
time
end
end
end
module CouchRest module CouchRest
module Model module Model
module Typecast module Typecast
@ -6,15 +29,12 @@ module CouchRest
return nil if value.nil? return nil if value.nil?
klass = property.type_class klass = property.type_class
if value.instance_of?(klass) || klass == Object if value.instance_of?(klass) || klass == Object
if klass == Time && !value.utc?
value.utc # Ensure Time is always in UTC
else
value value
end
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
property.build(value) # Allow the init_method to be defined as a Proc for advanced conversion
property.init_method.is_a?(Proc) ? property.init_method.call(value) : klass.send(property.init_method, value)
end end
end end
@ -59,7 +79,7 @@ module CouchRest
# Match numeric string # Match numeric string
def typecast_to_numeric(value, method) def typecast_to_numeric(value, method)
if value.respond_to?(:to_str) if value.respond_to?(:to_str)
if value.strip.gsub(/,/, '.').gsub(/\.(?!\d*\Z)/, '').to_str =~ /\A(-?(?:0|[1-9]\d*)(?:\.\d+)?|(?:\.\d+))\z/ if value.gsub(/,/, '.').gsub(/\.(?!\d*\Z)/, '').to_str =~ /\A(-?(?:0|[1-9]\d*)(?:\.\d+)?|(?:\.\d+))\z/
$1.send(method) $1.send(method)
else else
value value
@ -107,11 +127,12 @@ module CouchRest
if value.is_a?(Hash) if value.is_a?(Hash)
typecast_hash_to_time(value) typecast_hash_to_time(value)
else else
Time.parse_iso8601(value.to_s) Time.mktime_with_offset(value.to_s)
end end
rescue ArgumentError rescue ArgumentError
value value
rescue TypeError rescue TypeError
# After failures, resort to normal time parse
value value
end end
@ -129,7 +150,7 @@ module CouchRest
# Creates a Time instance from a Hash with keys :year, :month, :day, # Creates a Time instance from a Hash with keys :year, :month, :day,
# :hour, :min, :sec # :hour, :min, :sec
def typecast_hash_to_time(value) def typecast_hash_to_time(value)
Time.utc(*extract_time(value)) Time.local(*extract_time(value))
end end
# Extracts the given args from the hash. If a value does not exist, it # Extracts the given args from the hash. If a value does not exist, it

View file

@ -13,29 +13,18 @@ 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
# 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 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,57 +11,31 @@ 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)
opts = merge_view_options(attribute) view_name = options[:view].nil? ? "by_#{attribute}" : options[:view]
model = document.model_proxy || @model
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)
# Determine the base of the search # Determine the base of the search
base = opts[:proxy].nil? ? model : document.instance_eval(opts[:proxy]) base = options[:proxy].nil? ? model : document.instance_eval(options[:proxy])
if base.respond_to?(:has_view?) && !base.has_view?(opts[:view_name]) if base.respond_to?(:has_view?) && !base.has_view?(view_name)
raise "View #{document.class.name}.#{opts[:view_name]} does not exist for validation!" raise "View #{document.class.name}.#{options[:view]} does not exist!" unless options[:view].nil?
model.view_by attribute
end end
rows = base.view(opts[:view_name], :key => values, :limit => 2, :include_docs => false)['rows'] docs = base.view(view_name, :key => value, :limit => 2, :include_docs => false)['rows']
return if rows.empty? return if docs.empty?
unless document.new? unless document.new?
return if rows.find{|row| row['id'] == document.id} return if docs.find{|doc| doc['id'] == document.id}
end end
if rows.length > 0 if docs.length > 0
opts = options.merge(:value => value) document.errors.add(attribute, :taken, options.merge(:value => value))
opts.delete(:scope) # Has meaning with I18n!
document.errors.add(attribute, :taken, opts)
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,18 +72,16 @@ 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}')"
end end
keys.push opts keys.push opts
design_doc.view_by(*keys) design_doc.view_by(*keys)
req_design_doc_refresh
end end
# returns stored defaults if there is a view named this in the design doc # returns stored defaults if there is a view named this in the design doc
@ -101,9 +99,9 @@ module CouchRest
def view(name, query={}, &block) def view(name, query={}, &block)
query = query.dup # Modifications made on copy! query = query.dup # Modifications made on copy!
db = query.delete(:database) || database db = query.delete(:database) || database
refresh_design_doc(db)
query[:raw] = true if query[:reduce] query[:raw] = true if query[:reduce]
raw = query.delete(:raw) raw = query.delete(:raw)
save_design_doc(db)
fetch_view_with_docs(db, name, query, raw, &block) fetch_view_with_docs(db, name, query, raw, &block)
end end
@ -142,8 +140,21 @@ module CouchRest
def fetch_view(db, view_name, opts, &block) def fetch_view(db, view_name, opts, &block)
raise "A view needs a database to operate on (specify :database option, or use_database in the #{self.class} class)" unless db raise "A view needs a database to operate on (specify :database option, or use_database in the #{self.class} class)" unless db
retryable = true
begin
design_doc.view_on(db, view_name, opts, &block) design_doc.view_on(db, view_name, opts, &block)
# the design doc may not have been saved yet on this database
rescue RestClient::ResourceNotFound => e
if retryable
save_design_doc(db)
retryable = false
retry
else
raise e
end end
end
end
end # module ClassMethods end # module ClassMethods
end end

View file

@ -1,23 +1,11 @@
require "rails" require "rails"
require "active_model/railtie" require "active_model/railtie"
module CouchRest module CouchrestModel
class ModelRailtie < Rails::Railtie # = Active Record Railtie
def self.generator class Railtie < Rails::Railtie
config.respond_to?(:app_generators) ? :app_generators : :generators config.generators.orm :couchrest_model
end config.generators.test_framework :test_unit, :fixture => false
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,13 +1,13 @@
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"
require "active_model/translation" require "active_model/translation"
require "active_model/validator" require "active_model/validator"
require "active_model/validations" require "active_model/validations"
require "active_model/dirty"
require 'active_support/core_ext' require 'active_support/core_ext'
require 'active_support/json' require 'active_support/json'
@ -26,13 +26,10 @@ require 'couchrest/model'
require 'couchrest/model/errors' require 'couchrest/model/errors'
require "couchrest/model/persistence" require "couchrest/model/persistence"
require "couchrest/model/typecast" require "couchrest/model/typecast"
require "couchrest/model/casted_by"
require "couchrest/model/dirty"
require "couchrest/model/property" require "couchrest/model/property"
require "couchrest/model/property_protection" require "couchrest/model/property_protection"
require "couchrest/model/properties"
require "couchrest/model/casted_array" require "couchrest/model/casted_array"
require "couchrest/model/casted_hash" require "couchrest/model/properties"
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"
@ -44,23 +41,17 @@ 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"
require "couchrest/model/support/couchrest_database" require "couchrest/model/support/hash"
# Core Extensions
require "couchrest/model/core_extensions/hash"
require "couchrest/model/core_extensions/time_parsing"
# Base libraries # Base libraries
require "couchrest/model/embeddable" require "couchrest/model/casted_model"
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

@ -1,18 +0,0 @@
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

@ -1,21 +0,0 @@
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,37 +1,10 @@
# encoding: utf-8 # encoding: utf-8
require 'spec_helper' require File.expand_path('../../spec_helper', __FILE__)
require File.join(FIXTURE_PATH, 'more', 'sale_invoice')
describe "Assocations" do describe "Assocations" do
describe ".merge_belongs_to_association_options" do
before :all do
def SaleInvoice.merge_assoc_opts(*args)
merge_belongs_to_association_options(*args)
end
end
it "should return a default set of options" do
o = SaleInvoice.merge_assoc_opts(:cat)
o[:foreign_key].should eql('cat_id')
o[:class_name].should eql('Cat')
o[:proxy_name].should eql('cats')
o[:proxy].should eql('Cat') # same as class name
end
it "should merge with provided options" do
o = SaleInvoice.merge_assoc_opts(:cat, :foreign_key => 'somecat_id', :proxy => 'some_cats')
o[:foreign_key].should eql('somecat_id')
o[:proxy].should eql('some_cats')
end
it "should generate a proxy string if proxied" do
SaleInvoice.stub!(:proxy_owner_method).twice.and_return('company')
o = SaleInvoice.merge_assoc_opts(:cat)
o[:proxy].should eql('self.company.cats')
end
end
describe "of type belongs to" do describe "of type belongs to" do
before :each do before :each do
@ -70,6 +43,14 @@ describe "Assocations" do
@invoice.client @invoice.client
end end
it "should raise error if class name does not exist" do
lambda do
class TestBadAssoc < CouchRest::Model::Base
belongs_to :test_bad_item
end
end.should raise_error(NameError, /TestBadAssoc#test_bad_item/)
end
it "should allow override of foreign key" do it "should allow override of foreign key" do
@invoice.respond_to?(:alternate_client).should be_true @invoice.respond_to?(:alternate_client).should be_true
@invoice.respond_to?("alternate_client=").should be_true @invoice.respond_to?("alternate_client=").should be_true
@ -97,9 +78,9 @@ describe "Assocations" do
end end
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')
@invoice.respond_to?('entry_ids=').should be_true @invoice.respond_to?('entry_ids=')
@invoice.entries.class.should eql(::CouchRest::Model::CollectionOfProxy) @invoice.entries.class.should eql(::CouchRest::CollectionOfProxy)
end end
it "should allow replacement of objects" do it "should allow replacement of objects" do
@ -152,33 +133,6 @@ 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 'spec_helper' require File.expand_path('../../spec_helper', __FILE__)
describe "Model attachments" do describe "Model attachments" do

View file

@ -1,5 +1,11 @@
# 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
@ -38,48 +44,6 @@ 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
@ -121,22 +85,14 @@ 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 be_false @obj.persisted?.should == 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 be_true @obj.persisted?.should == 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
@ -148,57 +104,7 @@ 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
@ -321,7 +227,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', 'slug' => '1') @tmpl2 = WithTemplateAndUniqueID.new(:preset => 'not_value', 'important-field' => '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'
@ -340,12 +246,18 @@ describe "Model Base" do
describe "finding all instances of a model" do describe "finding all instances of a model" do
before(:all) do before(:all) do
WithTemplateAndUniqueID.req_design_doc_refresh
WithTemplateAndUniqueID.all.map{|o| o.destroy} WithTemplateAndUniqueID.all.map{|o| o.destroy}
WithTemplateAndUniqueID.database.bulk_delete WithTemplateAndUniqueID.database.bulk_delete
WithTemplateAndUniqueID.new('slug' => '1').save WithTemplateAndUniqueID.new('important-field' => '1').save
WithTemplateAndUniqueID.new('slug' => '2').save WithTemplateAndUniqueID.new('important-field' => '2').save
WithTemplateAndUniqueID.new('slug' => '3').save WithTemplateAndUniqueID.new('important-field' => '3').save
WithTemplateAndUniqueID.new('slug' => '4').save WithTemplateAndUniqueID.new('important-field' => '4').save
end
it "should make the design doc" do
WithTemplateAndUniqueID.all
d = WithTemplateAndUniqueID.design_doc
d['views']['all']['map'].should include('WithTemplateAndUniqueID')
end end
it "should find all" do it "should find all" do
rs = WithTemplateAndUniqueID.all rs = WithTemplateAndUniqueID.all
@ -356,6 +268,7 @@ describe "Model Base" do
describe "counting all instances of a model" do describe "counting all instances of a model" do
before(:each) do before(:each) do
@db = reset_test_db! @db = reset_test_db!
WithTemplateAndUniqueID.req_design_doc_refresh
end end
it ".count should return 0 if there are no docuemtns" do it ".count should return 0 if there are no docuemtns" do
@ -363,9 +276,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('slug' => '1').save WithTemplateAndUniqueID.new('important-field' => '1').save
WithTemplateAndUniqueID.new('slug' => '2').save WithTemplateAndUniqueID.new('important-field' => '2').save
WithTemplateAndUniqueID.new('slug' => '3').save WithTemplateAndUniqueID.new('important-field' => '3').save
WithTemplateAndUniqueID.count.should == 3 WithTemplateAndUniqueID.count.should == 3
end end
@ -374,14 +287,20 @@ 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('slug' => '1').save # WithTemplateAndUniqueID.req_design_doc_refresh # Removed by Sam Lown, design doc should be loaded automatically
WithTemplateAndUniqueID.new('slug' => '2').save WithTemplateAndUniqueID.new('important-field' => '1').save
WithTemplateAndUniqueID.new('slug' => '3').save WithTemplateAndUniqueID.new('important-field' => '2').save
WithTemplateAndUniqueID.new('slug' => '4').save WithTemplateAndUniqueID.new('important-field' => '3').save
WithTemplateAndUniqueID.new('important-field' => '4').save
end
it "should make the design doc" do
WithTemplateAndUniqueID.all
d = WithTemplateAndUniqueID.design_doc
d['views']['all']['map'].should include('WithTemplateAndUniqueID')
end end
it "should find first" do it "should find first" do
rs = WithTemplateAndUniqueID.first rs = WithTemplateAndUniqueID.first
rs['slug'].should == "1" rs['important-field'].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 }
@ -389,6 +308,21 @@ describe "Model Base" do
end end
end end
describe "lazily refreshing the design document" do
before(:all) do
@db = reset_test_db!
WithTemplateAndUniqueID.new('important-field' => '1').save
end
it "should not save the design doc twice" do
WithTemplateAndUniqueID.all
WithTemplateAndUniqueID.req_design_doc_refresh
WithTemplateAndUniqueID.refresh_design_doc
rev = WithTemplateAndUniqueID.design_doc['_rev']
WithTemplateAndUniqueID.req_design_doc_refresh
WithTemplateAndUniqueID.refresh_design_doc
WithTemplateAndUniqueID.design_doc['_rev'].should eql(rev)
end
end
describe "getting a model with a subobject field" do describe "getting a model with a subobject field" do
before(:all) do before(:all) do
@ -444,7 +378,6 @@ describe "Model Base" do
foundart.created_at.should == foundart.updated_at foundart.created_at.should == foundart.updated_at
end end
it "should set the time on update" do it "should set the time on update" do
@art.title = "new title" # only saved if @art.changed? == true
@art.save @art.save
@art.created_at.should < @art.updated_at @art.created_at.should < @art.updated_at
end end
@ -459,6 +392,13 @@ 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,25 +1,26 @@
# encoding: utf-8 # encoding: utf-8
require "spec_helper"
class WithCastedModelMixin require File.expand_path('../../spec_helper', __FILE__)
include CouchRest::Model::Embeddable 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', '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
@ -28,8 +29,8 @@ class DummyModel < CouchRest::Model::Base
end end
end end
class WithCastedCallBackModel class WithCastedCallBackModel < Hash
include CouchRest::Model::Embeddable include CouchRest::Model::CastedModel
property :name property :name
property :run_before_validation property :run_before_validation
property :run_after_validation property :run_after_validation
@ -50,7 +51,19 @@ class CastedCallbackDoc < CouchRest::Model::Base
property :callback_model, WithCastedCallBackModel property :callback_model, WithCastedCallBackModel
end end
describe CouchRest::Model::Embeddable do describe CouchRest::Model::CastedModel 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
@ -66,30 +79,6 @@ describe CouchRest::Model::Embeddable do
@obj.name.should == 'Eric' @obj.name.should == 'Eric'
@obj.details['color'].should == 'orange' @obj.details['color'].should == 'orange'
end end
it "should always return base_doc? as false" do
@obj.base_doc?.should be_false
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
@ -143,10 +132,6 @@ describe CouchRest::Model::Embeddable do
@casted_obj.casted_by.should == @obj @casted_obj.casted_by.should == @obj
end end
it "should know which property casted it" do
@casted_obj.casted_by_property.should == @obj.properties.detect{|p| p.to_s == 'casted_attribute'}
end
it "should return nil for the 'no_value' attribute" do it "should return nil for the 'no_value' attribute" do
@casted_obj.no_value.should be_nil @casted_obj.no_value.should be_nil
end end
@ -169,40 +154,13 @@ describe CouchRest::Model::Embeddable 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é'])
end end
it "should cast the array properly" do it "should cast the array properly" do
@obj.keywords.should be_kind_of(Array) @obj.keywords.should be_an_instance_of(Array)
@obj.keywords.first.should == 'couch' @obj.keywords.first.should == 'couch'
end end
end end

View file

@ -1,4 +1,7 @@
require "spec_helper" require File.expand_path('../../spec_helper', __FILE__)
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 "spec_helper" require File.expand_path("../../spec_helper", __FILE__)
class UnattachedDoc < CouchRest::Model::Base class UnattachedDoc < CouchRest::Model::Base
# Note: no use_database here # Note: no use_database here
@ -123,35 +123,6 @@ 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,9 +1,11 @@
require "spec_helper" require File.expand_path("../../spec_helper", __FILE__)
require File.join(FIXTURE_PATH, 'more', 'article')
describe "Collections" do describe "Collections" do
before(:all) do before(:all) do
reset_test_db! reset_test_db!
Article.refresh_design_doc
titles = ["very uniq one", "really interesting", "some fun", titles = ["very uniq one", "really interesting", "some fun",
"really awesome", "crazy bob", "this rocks", "super rad"] "really awesome", "crazy bob", "this rocks", "super rad"]
titles.each_with_index do |title,i| titles.each_with_index do |title,i|
@ -26,20 +28,21 @@ 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) :per_page => 3, :descending => true, :key => Date.today, :include_docs => true)
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) :per_page => 3, :page => 2, :descending => true, :key => Date.today, :include_docs => true)
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) :per_page => 3, :page => 3, :descending => true, :key => Date.today, :include_docs => true)
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,7 +1,8 @@
# encoding: utf-8 # encoding: utf-8
require "spec_helper" require File.expand_path('../../spec_helper', __FILE__)
require File.join(FIXTURE_PATH, 'more', 'cat')
describe CouchRest::Model::Configuration do describe CouchRest::Model::Base do
before do before do
@class = Class.new(CouchRest::Model::Base) @class = Class.new(CouchRest::Model::Base)
@ -58,7 +59,7 @@ describe CouchRest::Model::Configuration do
describe "General examples" do describe "General examples" do
before(:all) do before(:all) do
@default_model_key = 'model-type' @default_model_key = 'model'
end end

View file

@ -7,7 +7,6 @@ class DesignViewModel < CouchRest::Model::Base
design do design do
view :by_name view :by_name
view :by_just_name, :map => "function(doc) { emit(doc['name'], null); }"
end end
end end
@ -33,7 +32,7 @@ describe "Design View" do
@obj = @klass.new(DesignViewModel, {}, 'test_view') @obj = @klass.new(DesignViewModel, {}, 'test_view')
@obj.model.should eql(DesignViewModel) @obj.model.should eql(DesignViewModel)
@obj.name.should eql('test_view') @obj.name.should eql('test_view')
@obj.query.should be_empty @obj.query.should eql({:reduce => false})
end end
it "should complain if there is no name" do it "should complain if there is no name" do
@ -52,7 +51,7 @@ describe "Design View" do
it "should copy attributes" do it "should copy attributes" do
@obj.model.should eql(DesignViewModel) @obj.model.should eql(DesignViewModel)
@obj.name.should eql('test_view') @obj.name.should eql('test_view')
@obj.query.should eql({:foo => :bar}) @obj.query.should eql({:reduce => false, :foo => :bar})
end end
end end
@ -74,7 +73,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['#{DesignViewModel.model_type_key}'] == 'DesignViewModel') && (doc['title'] != null))") str.should include("((doc['couchrest-type'] == '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);")
@ -163,17 +162,10 @@ describe "Design View" do
end end
end end
describe "#length" do
it "should provide a length from the docs array" do
@obj.should_receive(:docs).and_return([1, 2, 3])
@obj.length.should eql(3)
end
end
describe "#count" do describe "#count" do
it "should raise an error if view prepared for group" do it "should raise an error if view prepared for group" do
@obj.should_receive(:query).and_return({:group => true}) @obj.should_receive(:query).and_return({:group => true})
lambda { @obj.count }.should raise_error(/group/) lambda { @obj.count }.should raise_error
end end
it "should return first row value if reduce possible" do it "should return first row value if reduce possible" do
@ -181,8 +173,6 @@ describe "Design View" do
row = mock("Row") row = mock("Row")
@obj.should_receive(:can_reduce?).and_return(true) @obj.should_receive(:can_reduce?).and_return(true)
@obj.should_receive(:reduce).and_return(view) @obj.should_receive(:reduce).and_return(view)
view.should_receive(:skip).with(0).and_return(view)
view.should_receive(:limit).with(1).and_return(view)
view.should_receive(:rows).and_return([row]) view.should_receive(:rows).and_return([row])
row.should_receive(:value).and_return(2) row.should_receive(:value).and_return(2)
@obj.count.should eql(2) @obj.count.should eql(2)
@ -191,8 +181,6 @@ describe "Design View" do
view = mock("SubView") view = mock("SubView")
@obj.should_receive(:can_reduce?).and_return(true) @obj.should_receive(:can_reduce?).and_return(true)
@obj.should_receive(:reduce).and_return(view) @obj.should_receive(:reduce).and_return(view)
view.should_receive(:skip).with(0).and_return(view)
view.should_receive(:limit).with(1).and_return(view)
view.should_receive(:rows).and_return([]) view.should_receive(:rows).and_return([])
@obj.count.should eql(0) @obj.count.should eql(0)
end end
@ -245,6 +233,15 @@ describe "Design View" do
end end
end end
describe "#keys" do
it "should request each row and provide key value" do
row = mock("Row")
row.should_receive(:key).twice.and_return('foo')
@obj.should_receive(:rows).and_return([row, row])
@obj.keys.should eql(['foo', 'foo'])
end
end
describe "#values" do describe "#values" do
it "should request each row and provide value" do it "should request each row and provide value" do
row = mock("Row") row = mock("Row")
@ -279,23 +276,19 @@ describe "Design View" do
@obj.should_receive(:update_query).with({:key => 'foo'}) @obj.should_receive(:update_query).with({:key => 'foo'})
@obj.key('foo') @obj.key('foo')
end end
it "should raise error if startkey set" do it "should raise and error if startkey set" do
@obj.query[:startkey] = 'bar' @obj.query[:startkey] = 'bar'
lambda { @obj.key('foo') }.should raise_error lambda { @obj.key('foo') }.should raise_error
end end
it "should raise error if endkey set" do it "should raise and error if endkey set" do
@obj.query[:endkey] = 'bar' @obj.query[:endkey] = 'bar'
lambda { @obj.key('foo') }.should raise_error lambda { @obj.key('foo') }.should raise_error
end end
it "should raise error if both startkey and endkey set" do it "should raise and error if both startkey and endkey set" do
@obj.query[:startkey] = 'bar' @obj.query[:startkey] = 'bar'
@obj.query[:endkey] = 'bar' @obj.query[:endkey] = 'bar'
lambda { @obj.key('foo') }.should raise_error lambda { @obj.key('foo') }.should raise_error
end end
it "should raise error if keys set" do
@obj.query[:keys] = 'bar'
lambda { @obj.key('foo') }.should raise_error
end
end end
describe "#startkey" do describe "#startkey" do
@ -305,11 +298,7 @@ describe "Design View" do
end end
it "should raise and error if key set" do it "should raise and error if key set" do
@obj.query[:key] = 'bar' @obj.query[:key] = 'bar'
lambda { @obj.startkey('foo') }.should raise_error(/View#startkey/) lambda { @obj.startkey('foo') }.should raise_error
end
it "should raise and error if keys set" do
@obj.query[:keys] = 'bar'
lambda { @obj.startkey('foo') }.should raise_error(/View#startkey/)
end end
end end
@ -333,11 +322,7 @@ describe "Design View" do
end end
it "should raise and error if key set" do it "should raise and error if key set" do
@obj.query[:key] = 'bar' @obj.query[:key] = 'bar'
lambda { @obj.endkey('foo') }.should raise_error(/View#endkey/) lambda { @obj.endkey('foo') }.should raise_error
end
it "should raise and error if keys set" do
@obj.query[:keys] = 'bar'
lambda { @obj.endkey('foo') }.should raise_error(/View#endkey/)
end end
end end
@ -354,56 +339,11 @@ describe "Design View" do
end end
end end
describe "#keys" do
it "should update the query" do
@obj.should_receive(:update_query).with({:keys => ['foo', 'bar']})
@obj.keys(['foo', 'bar'])
end
it "should raise and error if key set" do
@obj.query[:key] = 'bar'
lambda { @obj.keys('foo') }.should raise_error(/View#keys/)
end
it "should raise and error if startkey or endkey set" do
@obj.query[:startkey] = 'bar'
lambda { @obj.keys('foo') }.should raise_error(/View#keys/)
@obj.query.delete(:startkey)
@obj.query[:endkey] = 'bar'
lambda { @obj.keys('foo') }.should raise_error(/View#keys/)
end
end
describe "#keys (without parameters)" do
it "should request each row and provide key value" do
row = mock("Row")
row.should_receive(:key).twice.and_return('foo')
@obj.should_receive(:rows).and_return([row, row])
@obj.keys.should eql(['foo', 'foo'])
end
end
describe "#descending" do describe "#descending" do
it "should update query" do it "should update query" do
@obj.should_receive(:update_query).with({:descending => true}) @obj.should_receive(:update_query).with({:descending => true})
@obj.descending @obj.descending
end end
it "should reverse start and end keys if given" do
@obj = @obj.startkey('a').endkey('z')
@obj = @obj.descending
@obj.query[:endkey].should eql('a')
@obj.query[:startkey].should eql('z')
end
it "should reverse even if start or end nil" do
@obj = @obj.startkey('a')
@obj = @obj.descending
@obj.query[:endkey].should eql('a')
@obj.query[:startkey].should be_nil
end
it "should reverse start_doc and end_doc keys if given" do
@obj = @obj.startkey_doc('a').endkey_doc('z')
@obj = @obj.descending
@obj.query[:endkey_docid].should eql('a')
@obj.query[:startkey_docid].should eql('z')
end
end end
describe "#limit" do describe "#limit" do
@ -557,7 +497,6 @@ describe "Design View" do
# disable real execution! # disable real execution!
@design_doc = mock("DesignDoc") @design_doc = mock("DesignDoc")
@design_doc.stub!(:view_on) @design_doc.stub!(:view_on)
@obj.model.stub!(:save_design_doc)
@obj.model.stub!(:design_doc).and_return(@design_doc) @obj.model.stub!(:design_doc).and_return(@design_doc)
end end
@ -580,12 +519,6 @@ describe "Design View" do
@obj.send(:execute) @obj.send(:execute)
end end
it "should call to save the design document" do
@obj.should_receive(:can_reduce?).and_return(false)
@obj.model.should_receive(:save_design_doc).with(DB)
@obj.send(:execute)
end
it "should populate the results" do it "should populate the results" do
@obj.should_receive(:can_reduce?).and_return(true) @obj.should_receive(:can_reduce?).and_return(true)
@design_doc.should_receive(:view_on).and_return('foos') @design_doc.should_receive(:view_on).and_return('foos')
@ -593,6 +526,22 @@ describe "Design View" do
@obj.result.should eql('foos') @obj.result.should eql('foos')
end end
it "should retry once on a resource not found error" do
@obj.should_receive(:can_reduce?).and_return(true)
@obj.model.should_receive(:save_design_doc)
@design_doc.should_receive(:view_on).ordered.and_raise(RestClient::ResourceNotFound)
@design_doc.should_receive(:view_on).ordered.and_return('foos')
@obj.send(:execute)
@obj.result.should eql('foos')
end
it "should retry twice and fail on a resource not found error" do
@obj.should_receive(:can_reduce?).and_return(true)
@obj.model.should_receive(:save_design_doc)
@design_doc.should_receive(:view_on).twice.and_raise(RestClient::ResourceNotFound)
lambda { @obj.send(:execute) }.should raise_error(RestClient::ResourceNotFound)
end
it "should remove nil values from query" do it "should remove nil values from query" do
@obj.should_receive(:can_reduce?).and_return(true) @obj.should_receive(:can_reduce?).and_return(true)
@obj.stub!(:use_database).and_return('database') @obj.stub!(:use_database).and_return('database')
@ -751,6 +700,7 @@ describe "Design View" do
end end
describe "loading documents" do describe "loading documents" do
it "should return first" do it "should return first" do
DesignViewModel.by_name.first.name.should eql("Judith") DesignViewModel.by_name.first.name.should eql("Judith")
end end
@ -765,6 +715,7 @@ describe "Design View" do
view.last.name.should eql("Peter") view.last.name.should eql("Peter")
view.all.length.should eql(3) view.all.length.should eql(3)
end end
end end
describe "index information" do describe "index information" do
@ -782,22 +733,6 @@ describe "Design View" do
end end
end end
describe "viewing" do
it "should load views with no reduce method" do
docs = DesignViewModel.by_just_name.all
docs.length.should eql(5)
end
it "should load documents by specific keys" do
docs = DesignViewModel.by_name.keys(["Judith", "Peter"]).all
docs[0].name.should eql("Judith")
docs[1].name.should eql("Peter")
end
it "should provide count even if limit or skip set" do
docs = DesignViewModel.by_name.limit(20).skip(2)
docs.count.should eql(5)
end
end
describe "pagination" do describe "pagination" do
before :all do before :all do
DesignViewModel.paginates_per 3 DesignViewModel.paginates_per 3

View file

@ -1,9 +1,10 @@
require "spec_helper" require File.expand_path("../../spec_helper", __FILE__)
class DesignModel < CouchRest::Model::Base class DesignModel < CouchRest::Model::Base
end end
describe CouchRest::Model::Designs do describe "Design" 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
@ -30,6 +31,11 @@ describe CouchRest::Model::Designs do
DesignModel.design { foo } DesignModel.design { foo }
end end
it "should request a design refresh" do
DesignModel.should_receive(:req_design_doc_refresh)
DesignModel.design() { }
end
it "should work even if a block is not provided" do it "should work even if a block is not provided" do
lambda { DesignModel.design }.should_not raise_error lambda { DesignModel.design }.should_not raise_error
end end
@ -83,36 +89,6 @@ describe CouchRest::Model::Designs 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

@ -0,0 +1,40 @@
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

View file

@ -1,7 +1,12 @@
# encoding: utf-8 # encoding: utf-8
require 'spec_helper' require File.expand_path('../../spec_helper', __FILE__)
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 CouchRest::Model::Persistence do describe "Model Persistence" do
before(:each) do before(:each) do
@obj = WithDefaultValues.new @obj = WithDefaultValues.new
@ -29,8 +34,8 @@ describe CouchRest::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
@ -76,18 +81,6 @@ describe CouchRest::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
@ -217,34 +210,34 @@ describe CouchRest::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['slug'] = 'very-important' @templated['important-field'] = '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['slug'] = 'very-important' @templated['important-field'] = '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['slug'] = 'very-important' @templated['important-field'] = 'very-important'
@templated.save.should be_true @templated.save.should be_true
@templated['slug'] = 'not-important' @templated['important-field'] = '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.should == @templated
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['slug'] = 'very-important' @templated['important-field'] = 'very-important'
@templated.save.should be_true @templated.save.should be_true
lambda{WithTemplateAndUniqueID.new('slug' => 'very-important').save}.should raise_error lambda{WithTemplateAndUniqueID.new('important-field' => 'very-important').save}.should raise_error
end end
it "should set the id" do it "should set the id" do
@templated['slug'] = 'very-important' @templated['important-field'] = 'very-important'
@templated.save.should be_true @templated.save.should be_true
@templated.id.should == 'very-important' @templated.id.should == 'very-important'
end end
@ -252,31 +245,22 @@ describe CouchRest::Model::Persistence do
describe "destroying an instance" do describe "destroying an instance" do
before(:each) do before(:each) do
@dobj = Event.new @dobj = Basic.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(CouchRest::Model::DocumentNotFound) lambda{Basic.get!(@dobj.id)}.should raise_error
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
@ -356,27 +340,6 @@ describe CouchRest::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 "spec_helper" require File.expand_path("../../spec_helper", __FILE__)
describe "Model Attributes" do describe "Model Attributes" do

View file

@ -0,0 +1,877 @@
# encoding: utf-8
require File.expand_path('../../spec_helper', __FILE__)
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 "Model properties" do
before(:each) do
reset_test_db!
@card = Card.new(:first_name => "matt")
end
it "should be accessible from the object" do
@card.properties.should be_an_instance_of(Array)
@card.properties.map{|p| p.name}.should include("first_name")
end
it "should list object properties with values" do
@card.properties_with_values.should be_an_instance_of(Hash)
@card.properties_with_values["first_name"].should == "matt"
end
it "should let you access a property value (getter)" do
@card.first_name.should == "matt"
end
it "should let you set a property value (setter)" do
@card.last_name = "Aimonetti"
@card.last_name.should == "Aimonetti"
end
it "should not let you set a property value if it's read only" do
lambda{@card.read_only_value = "test"}.should raise_error
end
it "should let you use an alias for an attribute" do
@card.last_name = "Aimonetti"
@card.family_name.should == "Aimonetti"
@card.family_name.should == @card.last_name
end
it "should let you use an alias for a casted attribute" do
@card.cast_alias = Person.new(:name => ["Aimonetti"])
@card.cast_alias.name.should == ["Aimonetti"]
@card.calias.name.should == ["Aimonetti"]
card = Card.new(:first_name => "matt", :cast_alias => {:name => ["Aimonetti"]})
card.cast_alias.name.should == ["Aimonetti"]
card.calias.name.should == ["Aimonetti"]
end
it "should be auto timestamped" do
@card.created_at.should be_nil
@card.updated_at.should be_nil
@card.save.should be_true
@card.created_at.should_not be_nil
@card.updated_at.should_not be_nil
end
describe '#read_attribute' do
it "should let you use read_attribute method" do
@card.last_name = "Aimonetti"
@card.read_attribute(:last_name).should eql('Aimonetti')
@card.read_attribute('last_name').should eql('Aimonetti')
last_name_prop = @card.properties.find{|p| p.name == 'last_name'}
@card.read_attribute(last_name_prop).should eql('Aimonetti')
end
it 'should raise an error if the property does not exist' do
expect { @card.read_attribute(:this_property_should_not_exist) }.to raise_error(ArgumentError)
end
end
describe '#write_attribute' do
it "should let you use write_attribute method" do
@card.write_attribute(:last_name, 'Aimonetti 1')
@card.last_name.should eql('Aimonetti 1')
@card.write_attribute('last_name', 'Aimonetti 2')
@card.last_name.should eql('Aimonetti 2')
last_name_prop = @card.properties.find{|p| p.name == 'last_name'}
@card.write_attribute(last_name_prop, 'Aimonetti 3')
@card.last_name.should eql('Aimonetti 3')
end
it 'should raise an error if the property does not exist' do
expect { @card.write_attribute(:this_property_should_not_exist, 823) }.to raise_error(ArgumentError)
end
it "should let you use write_attribute on readonly properties" do
lambda {
@card.read_only_value = "foo"
}.should raise_error
@card.write_attribute(:read_only_value, "foo")
@card.read_only_value.should == 'foo'
end
it "should cast via write_attribute" do
@card.write_attribute(:cast_alias, {:name => ["Sam", "Lown"]})
@card.cast_alias.class.should eql(Person)
@card.cast_alias.name.last.should eql("Lown")
end
it "should not cast via write_attribute if property not casted" do
@card.write_attribute(:first_name, {:name => "Sam"})
@card.first_name.class.should eql(Hash)
@card.first_name[:name].should eql("Sam")
end
end
describe "mass updating attributes without property" do
describe "when mass_assign_any_attribute false" do
it "should not allow them to be set" do
@card.attributes = {:test => 'fooobar'}
@card['test'].should be_nil
end
end
describe "when mass_assign_any_attribute true" do
before(:each) do
# dup Card class so that no other tests are effected
card_class = Card.dup
card_class.class_eval do
mass_assign_any_attribute true
end
@card = card_class.new(:first_name => 'Sam')
end
it 'should allow them to be updated' do
@card.attributes = {:test => 'fooobar'}
@card['test'].should eql('fooobar')
end
end
end
describe "mass assignment protection" do
it "should not store protected attribute using mass assignment" do
cat_toy = CatToy.new(:name => "Zorro")
cat = Cat.create(:name => "Helena", :toys => [cat_toy], :favorite_toy => cat_toy, :number => 1)
cat.number.should be_nil
cat.number = 1
cat.save
cat.number.should == 1
end
it "should not store protected attribute when 'declare accessible poperties, assume all the rest are protected'" do
user = User.create(:name => "Marcos Tapajós", :admin => true)
user.admin.should be_nil
end
it "should not store protected attribute when 'declare protected properties, assume all the rest are accessible'" do
user = SpecialUser.create(:name => "Marcos Tapajós", :admin => true)
user.admin.should be_nil
end
end
describe "validation" do
before(:each) do
@invoice = Invoice.new(:client_name => "matt", :employee_name => "Chris", :location => "San Diego, CA")
end
it "should be able to be validated" do
@card.valid?.should == true
end
it "should let you validate the presence of an attribute" do
@card.first_name = nil
@card.should_not be_valid
@card.errors.should_not be_empty
@card.errors[:first_name].should == ["can't be blank"]
end
it "should let you look up errors for a field by a string name" do
@card.first_name = nil
@card.should_not be_valid
@card.errors['first_name'].should == ["can't be blank"]
end
it "should validate the presence of 2 attributes" do
@invoice.clear
@invoice.should_not be_valid
@invoice.errors.should_not be_empty
@invoice.errors[:client_name].should == ["can't be blank"]
@invoice.errors[:employee_name].should_not be_empty
end
it "should let you set an error message" do
@invoice.location = nil
@invoice.valid?
@invoice.errors[:location].should == ["Hey stupid!, you forgot the location"]
end
it "should validate before saving" do
@invoice.location = nil
@invoice.should_not be_valid
@invoice.save.should be_false
@invoice.should be_new
end
end
describe "casting" do
before(:each) do
@course = Course.new(:title => 'Relaxation')
end
describe "when value is nil" do
it "leaves the value unchanged" do
@course.title = nil
@course['title'].should == nil
end
end
describe "when type primitive is an Object" do
it "it should not cast given value" do
@course.participants = [{}, 'q', 1]
@course['participants'].should == [{}, 'q', 1]
end
it "should cast started_on to Date" do
@course.started_on = Date.today
@course['started_on'].should be_an_instance_of(Date)
end
end
describe "when type primitive is a String" do
it "keeps string value unchanged" do
value = "1.0"
@course.title = value
@course['title'].should equal(value)
end
it "it casts to string representation of the value" do
@course.title = 1.0
@course['title'].should eql("1.0")
end
end
describe 'when type primitive is a Float' do
it 'returns same value if a float' do
value = 24.0
@course.estimate = value
@course['estimate'].should equal(value)
end
it 'returns float representation of a zero string integer' do
@course.estimate = '0'
@course['estimate'].should eql(0.0)
end
it 'returns float representation of a positive string integer' do
@course.estimate = '24'
@course['estimate'].should eql(24.0)
end
it 'returns float representation of a negative string integer' do
@course.estimate = '-24'
@course['estimate'].should eql(-24.0)
end
it 'returns float representation of a zero string float' do
@course.estimate = '0.0'
@course['estimate'].should eql(0.0)
end
it 'returns float representation of a positive string float' do
@course.estimate = '24.35'
@course['estimate'].should eql(24.35)
end
it 'returns float representation of a negative string float' do
@course.estimate = '-24.35'
@course['estimate'].should eql(-24.35)
end
it 'returns float representation of a zero string float, with no leading digits' do
@course.estimate = '.0'
@course['estimate'].should eql(0.0)
end
it 'returns float representation of a positive string float, with no leading digits' do
@course.estimate = '.41'
@course['estimate'].should eql(0.41)
end
it 'returns float representation of a zero integer' do
@course.estimate = 0
@course['estimate'].should eql(0.0)
end
it 'returns float representation of a positive integer' do
@course.estimate = 24
@course['estimate'].should eql(24.0)
end
it 'returns float representation of a negative integer' do
@course.estimate = -24
@course['estimate'].should eql(-24.0)
end
it 'returns float representation of a zero decimal' do
@course.estimate = BigDecimal('0.0')
@course['estimate'].should eql(0.0)
end
it 'returns float representation of a positive decimal' do
@course.estimate = BigDecimal('24.35')
@course['estimate'].should eql(24.35)
end
it 'returns float representation of a negative decimal' do
@course.estimate = BigDecimal('-24.35')
@course['estimate'].should eql(-24.35)
end
it 'return float of a number with commas instead of points for decimals' do
@course.estimate = '23,35'
@course['estimate'].should eql(23.35)
end
it "should handle numbers with commas and points" do
@course.estimate = '1,234.00'
@course.estimate.should eql(1234.00)
end
it "should handle a mis-match of commas and points and maintain the last one" do
@course.estimate = "1,232.434.123,323"
@course.estimate.should eql(1232434123.323)
end
[ Object.new, true, '00.0', '0.', '-.0', 'string' ].each do |value|
it "does not typecast non-numeric value #{value.inspect}" do
@course.estimate = value
@course['estimate'].should equal(value)
end
end
end
describe 'when type primitive is a Integer' do
it 'returns same value if an integer' do
value = 24
@course.hours = value
@course['hours'].should equal(value)
end
it 'returns integer representation of a zero string integer' do
@course.hours = '0'
@course['hours'].should eql(0)
end
it 'returns integer representation of a positive string integer' do
@course.hours = '24'
@course['hours'].should eql(24)
end
it 'returns integer representation of a negative string integer' do
@course.hours = '-24'
@course['hours'].should eql(-24)
end
it 'returns integer representation of a zero string float' do
@course.hours = '0.0'
@course['hours'].should eql(0)
end
it 'returns integer representation of a positive string float' do
@course.hours = '24.35'
@course['hours'].should eql(24)
end
it 'returns integer representation of a negative string float' do
@course.hours = '-24.35'
@course['hours'].should eql(-24)
end
it 'returns integer representation of a zero string float, with no leading digits' do
@course.hours = '.0'
@course['hours'].should eql(0)
end
it 'returns integer representation of a positive string float, with no leading digits' do
@course.hours = '.41'
@course['hours'].should eql(0)
end
it 'returns integer representation of a zero float' do
@course.hours = 0.0
@course['hours'].should eql(0)
end
it 'returns integer representation of a positive float' do
@course.hours = 24.35
@course['hours'].should eql(24)
end
it 'returns integer representation of a negative float' do
@course.hours = -24.35
@course['hours'].should eql(-24)
end
it 'returns integer representation of a zero decimal' do
@course.hours = '0.0'
@course['hours'].should eql(0)
end
it 'returns integer representation of a positive decimal' do
@course.hours = '24.35'
@course['hours'].should eql(24)
end
it 'returns integer representation of a negative decimal' do
@course.hours = '-24.35'
@course['hours'].should eql(-24)
end
[ Object.new, true, '00.0', '0.', '-.0', 'string' ].each do |value|
it "does not typecast non-numeric value #{value.inspect}" do
@course.hours = value
@course['hours'].should equal(value)
end
end
end
describe 'when type primitive is a BigDecimal' do
it 'returns same value if a decimal' do
value = BigDecimal('24.0')
@course.profit = value
@course['profit'].should equal(value)
end
it 'returns decimal representation of a zero string integer' do
@course.profit = '0'
@course['profit'].should eql(BigDecimal('0.0'))
end
it 'returns decimal representation of a positive string integer' do
@course.profit = '24'
@course['profit'].should eql(BigDecimal('24.0'))
end
it 'returns decimal representation of a negative string integer' do
@course.profit = '-24'
@course['profit'].should eql(BigDecimal('-24.0'))
end
it 'returns decimal representation of a zero string float' do
@course.profit = '0.0'
@course['profit'].should eql(BigDecimal('0.0'))
end
it 'returns decimal representation of a positive string float' do
@course.profit = '24.35'
@course['profit'].should eql(BigDecimal('24.35'))
end
it 'returns decimal representation of a negative string float' do
@course.profit = '-24.35'
@course['profit'].should eql(BigDecimal('-24.35'))
end
it 'returns decimal representation of a zero string float, with no leading digits' do
@course.profit = '.0'
@course['profit'].should eql(BigDecimal('0.0'))
end
it 'returns decimal representation of a positive string float, with no leading digits' do
@course.profit = '.41'
@course['profit'].should eql(BigDecimal('0.41'))
end
it 'returns decimal representation of a zero integer' do
@course.profit = 0
@course['profit'].should eql(BigDecimal('0.0'))
end
it 'returns decimal representation of a positive integer' do
@course.profit = 24
@course['profit'].should eql(BigDecimal('24.0'))
end
it 'returns decimal representation of a negative integer' do
@course.profit = -24
@course['profit'].should eql(BigDecimal('-24.0'))
end
it 'returns decimal representation of a zero float' do
@course.profit = 0.0
@course['profit'].should eql(BigDecimal('0.0'))
end
it 'returns decimal representation of a positive float' do
@course.profit = 24.35
@course['profit'].should eql(BigDecimal('24.35'))
end
it 'returns decimal representation of a negative float' do
@course.profit = -24.35
@course['profit'].should eql(BigDecimal('-24.35'))
end
[ Object.new, true, '00.0', '0.', '-.0', 'string' ].each do |value|
it "does not typecast non-numeric value #{value.inspect}" do
@course.profit = value
@course['profit'].should equal(value)
end
end
end
describe 'when type primitive is a DateTime' do
describe 'and value given as a hash with keys like :year, :month, etc' do
it 'builds a DateTime instance from hash values' do
@course.updated_at = {
:year => '2006',
:month => '11',
:day => '23',
:hour => '12',
:min => '0',
:sec => '0'
}
result = @course['updated_at']
result.should be_kind_of(DateTime)
result.year.should eql(2006)
result.month.should eql(11)
result.day.should eql(23)
result.hour.should eql(12)
result.min.should eql(0)
result.sec.should eql(0)
end
end
describe 'and value is a string' do
it 'parses the string' do
@course.updated_at = 'Dec, 2006'
@course['updated_at'].month.should == 12
end
end
it 'does not typecast non-datetime values' do
@course.updated_at = 'not-datetime'
@course['updated_at'].should eql('not-datetime')
end
end
describe 'when type primitive is a Date' do
describe 'and value given as a hash with keys like :year, :month, etc' do
it 'builds a Date instance from hash values' do
@course.started_on = {
:year => '2007',
:month => '3',
:day => '25'
}
result = @course['started_on']
result.should be_kind_of(Date)
result.year.should eql(2007)
result.month.should eql(3)
result.day.should eql(25)
end
end
describe 'and value is a string' do
it 'parses the string' do
@course.started_on = 'Dec 20th, 2006'
@course.started_on.month.should == 12
@course.started_on.day.should == 20
@course.started_on.year.should == 2006
end
end
it 'does not typecast non-date values' do
@course.started_on = 'not-date'
@course['started_on'].should eql('not-date')
end
end
describe 'when type primitive is a Time' do
describe 'and value given as a hash with keys like :year, :month, etc' do
it 'builds a Time instance from hash values' do
@course.ends_at = {
:year => '2006',
:month => '11',
:day => '23',
:hour => '12',
:min => '0',
:sec => '0'
}
result = @course['ends_at']
result.should be_kind_of(Time)
result.year.should eql(2006)
result.month.should eql(11)
result.day.should eql(23)
result.hour.should eql(12)
result.min.should eql(0)
result.sec.should eql(0)
end
end
describe 'and value is a string' do
it 'parses the string' do
t = Time.now
@course.ends_at = t.strftime('%Y/%m/%d %H:%M:%S %z')
@course['ends_at'].year.should eql(t.year)
@course['ends_at'].month.should eql(t.month)
@course['ends_at'].day.should eql(t.day)
@course['ends_at'].hour.should eql(t.hour)
@course['ends_at'].min.should eql(t.min)
@course['ends_at'].sec.should eql(t.sec)
end
it 'parses the string without offset' do
t = Time.now
@course.ends_at = t.strftime("%Y-%m-%d %H:%M:%S")
@course['ends_at'].year.should eql(t.year)
@course['ends_at'].month.should eql(t.month)
@course['ends_at'].day.should eql(t.day)
@course['ends_at'].hour.should eql(t.hour)
@course['ends_at'].min.should eql(t.min)
@course['ends_at'].sec.should eql(t.sec)
end
end
it 'does not typecast non-time values' do
@course.ends_at = 'not-time'
@course['ends_at'].should eql('not-time')
end
end
describe 'when type primitive is a Class' do
it 'returns same value if a class' do
value = Course
@course.klass = value
@course['klass'].should equal(value)
end
it 'returns the class if found' do
@course.klass = 'Course'
@course['klass'].should eql(Course)
end
it 'does not typecast non-class values' do
@course.klass = 'NoClass'
@course['klass'].should eql('NoClass')
end
end
describe 'when type primitive is a Boolean' do
[ true, 'true', 'TRUE', '1', 1, 't', 'T' ].each do |value|
it "returns true when value is #{value.inspect}" do
@course.active = value
@course['active'].should be_true
end
end
[ false, 'false', 'FALSE', '0', 0, 'f', 'F' ].each do |value|
it "returns false when value is #{value.inspect}" do
@course.active = value
@course['active'].should be_false
end
end
[ 'string', 2, 1.0, BigDecimal('1.0'), DateTime.now, Time.now, Date.today, Class, Object.new, ].each do |value|
it "does not typecast value #{value.inspect}" do
@course.active = value
@course['active'].should equal(value)
end
end
it "should respond to requests with ? modifier" do
@course.active = nil
@course.active?.should be_false
@course.active = false
@course.active?.should be_false
@course.active = true
@course.active?.should be_true
end
it "should respond to requests with ? modifier on TrueClass" do
@course.very_active = nil
@course.very_active?.should be_false
@course.very_active = false
@course.very_active?.should be_false
@course.very_active = true
@course.very_active?.should be_true
end
end
end
end
describe "properties of array of casted models" do
before(:each) do
@course = Course.new :title => 'Test Course'
end
it "should allow attribute to be set from an array of objects" do
@course.questions = [Question.new(:q => "works?"), Question.new(:q => "Meaning of Life?")]
@course.questions.length.should eql(2)
end
it "should allow attribute to be set from an array of hashes" do
@course.questions = [{:q => "works?"}, {:q => "Meaning of Life?"}]
@course.questions.length.should eql(2)
@course.questions.last.q.should eql("Meaning of Life?")
@course.questions.last.class.should eql(Question) # typecasting
end
it "should allow attribute to be set from hash with ordered keys and objects" do
@course.questions = { '0' => Question.new(:q => "Test1"), '1' => Question.new(:q => 'Test2') }
@course.questions.length.should eql(2)
@course.questions.last.q.should eql('Test2')
@course.questions.last.class.should eql(Question)
end
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.length.should eql(2)
@course.questions.last.q.should eql('Test2')
@course.questions.last.class.should eql(Question)
end
it "should allow attribute to be set from hash with ordered keys and HashWithIndifferentAccess" do
# This is similar to what you'd find in an HTML POST parameters
hash = HashWithIndifferentAccess.new({ '0' => {:q => "Test1"}, '1' => {:q => 'Test2'} })
@course.questions = hash
@course.questions.length.should eql(2)
@course.questions.last.q.should eql('Test2')
@course.questions.last.class.should eql(Question)
end
it "should raise an error if attempting to set single value for array type" do
lambda {
@course.questions = Question.new(:q => 'test1')
}.should raise_error
end
end
describe "a casted model retrieved from the database" do
before(:each) do
reset_test_db!
@cat = Cat.new(:name => 'Stimpy')
@cat.favorite_toy = CatToy.new(:name => 'Stinky')
@cat.toys << CatToy.new(:name => 'Feather')
@cat.toys << CatToy.new(:name => 'Mouse')
@cat.save
@cat = Cat.get(@cat.id)
end
describe "as a casted property" do
it "should already be casted_by its parent" do
@cat.favorite_toy.casted_by.should === @cat
end
end
describe "from a casted collection" do
it "should already be casted_by its parent" do
@cat.toys[0].casted_by.should === @cat
@cat.toys[1].casted_by.should === @cat
end
end
end
describe "Property Class" do
it "should provide name as string" do
property = CouchRest::Model::Property.new(:test, String)
property.name.should eql('test')
property.to_s.should eql('test')
end
it "should provide class from type" do
property = CouchRest::Model::Property.new(:test, String)
property.type_class.should eql(String)
end
it "should provide base class from type in array" do
property = CouchRest::Model::Property.new(:test, [String])
property.type_class.should eql(String)
end
it "should raise error if type as string requested" do
lambda {
property = CouchRest::Model::Property.new(:test, 'String')
}.should raise_error
end
it "should leave type nil and return class as nil also" do
property = CouchRest::Model::Property.new(:test, nil)
property.type.should be_nil
property.type_class.should be_nil
end
it "should convert empty type array to [Object]" do
property = CouchRest::Model::Property.new(:test, [])
property.type_class.should eql(Object)
end
it "should set init method option or leave as 'new'" do
# (bad example! Time already typecast)
property = CouchRest::Model::Property.new(:test, Time)
property.init_method.should eql('new')
property = CouchRest::Model::Property.new(:test, Time, :init_method => 'parse')
property.init_method.should eql('parse')
end
## Property Casting method. More thoroughly tested earlier.
describe "casting" do
it "should cast a value" do
property = CouchRest::Model::Property.new(:test, Date)
parent = mock("FooObject")
property.cast(parent, "2010-06-16").should eql(Date.new(2010, 6, 16))
property.cast_value(parent, "2010-06-16").should eql(Date.new(2010, 6, 16))
end
it "should cast an array of values" do
property = CouchRest::Model::Property.new(:test, [Date])
parent = mock("FooObject")
property.cast(parent, ["2010-06-01", "2010-06-02"]).should eql([Date.new(2010, 6, 1), Date.new(2010, 6, 2)])
end
it "should set a CastedArray on array of Objects" do
property = CouchRest::Model::Property.new(:test, [Object])
parent = mock("FooObject")
property.cast(parent, ["2010-06-01", "2010-06-02"]).class.should eql(CouchRest::Model::CastedArray)
end
it "should not set a CastedArray on array of Strings" do
property = CouchRest::Model::Property.new(:test, [String])
parent = mock("FooObject")
property.cast(parent, ["2010-06-01", "2010-06-02"]).class.should_not eql(CouchRest::Model::CastedArray)
end
it "should raise and error if value is array when type is not" do
property = CouchRest::Model::Property.new(:test, Date)
parent = mock("FooClass")
lambda {
cast = property.cast(parent, [Date.new(2010, 6, 1)])
}.should raise_error
end
it "should set parent as casted_by object in CastedArray" do
property = CouchRest::Model::Property.new(:test, [Object])
parent = mock("FooObject")
property.cast(parent, ["2010-06-01", "2010-06-02"]).casted_by.should eql(parent)
end
it "should set casted_by on new value" do
property = CouchRest::Model::Property.new(:test, CatToy)
parent = mock("CatObject")
cast = property.cast(parent, {:name => 'catnip'})
cast.casted_by.should eql(parent)
end
end
end

View file

@ -1,77 +1,28 @@
require "spec_helper" require File.expand_path("../../spec_helper", __FILE__)
require File.join(FIXTURE_PATH, 'more', 'cat')
class DummyProxyable < CouchRest::Model::Base class DummyProxyable < CouchRest::Model::Base
proxy_database_method :db def proxy_database
def db 'db' # Do not use this!
'db'
end end
end end
class ProxyKitten < CouchRest::Model::Base class ProxyKitten < CouchRest::Model::Base
end end
describe CouchRest::Model::Proxyable do describe "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
it "should provide #model_proxy method" do
DummyProxyable.new.should respond_to(:model_proxy)
end end
describe "class methods" do describe "class methods" do
describe ".proxy_owner_method" do
before(:each) do
@class = DummyProxyable.clone
end
it "should provide proxy_owner_method accessors" do
@class.should respond_to(:proxy_owner_method)
@class.should respond_to(:proxy_owner_method=)
end
it "should work as expected" do
@class.proxy_owner_method = "foo"
@class.proxy_owner_method.should eql("foo")
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) DummyProxyable.should respond_to(:proxy_for)
end end
it "should create a new method" do it "should create a new method" do
@ -85,7 +36,8 @@ describe CouchRest::Model::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
@ -97,49 +49,43 @@ describe CouchRest::Model::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
DummyProxyable.proxy_for(:cats)
@obj = DummyProxyable.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 end
it "should raise an error if custom database method missing" do
DummyProxyable.proxy_for(:proxy_kittens, :database_method => "foobardom")
@obj = DummyProxyable.new
lambda { @obj.proxy_kittens }.should raise_error(StandardError, "Missing #foobardom method for proxy")
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) DummyProxyable.should respond_to(:proxied_by)
end end
it "should add an attribute accessor" do it "should add an attribute accessor" do
@class.proxied_by(:foobar) DummyProxyable.proxied_by(:foobar)
@class.new.should respond_to(:foobar) DummyProxyable.new.should respond_to(:foobar)
end
it "should provide #model_proxy method" do
@class.proxied_by(:foobar)
@class.new.should respond_to(:model_proxy)
end
it "should set the proxy_owner_method" do
@class.proxied_by(:foobar)
@class.proxy_owner_method.should eql(:foobar)
end end
it "should raise an error if model name pre-defined" do it "should raise an error if model name pre-defined" do
lambda { @class.proxied_by(:object_id) }.should raise_error lambda { DummyProxyable.proxied_by(:object_id) }.should raise_error
end
end end
it "should raise an error if object already has a proxy" do
@class.proxied_by(:department)
lambda { @class.proxied_by(:company) }.should raise_error
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
describe "ModelProxy" do describe "ModelProxy" do
@ -163,13 +109,15 @@ describe CouchRest::Model::Proxyable do
end end
it "should proxy new call" do it "should proxy new call" do
@obj.should_receive(:proxy_block_update).with(:new, 'attrs', 'opts') Cat.should_receive(:new).and_return({})
@obj.new('attrs', 'opts') @obj.should_receive(:proxy_update).and_return(true)
@obj.new
end end
it "should proxy build_from_database" do it "should proxy build_from_database" do
@obj.should_receive(:proxy_block_update).with(:build_from_database, 'attrs', 'opts') Cat.should_receive(:build_from_database).and_return({})
@obj.build_from_database('attrs', 'opts') @obj.should_receive(:proxy_update).with({}).and_return(true)
@obj.build_from_database
end end
describe "#method_missing" do describe "#method_missing" do
@ -263,6 +211,17 @@ describe CouchRest::Model::Proxyable do
@obj.design_doc @obj.design_doc
end end
describe "#refresh_design_doc" do
it "should be proxied without database arg" do
Cat.should_receive(:refresh_design_doc).with('database')
@obj.refresh_design_doc
end
it "should be proxied with database arg" do
Cat.should_receive(:refresh_design_doc).with('db')
@obj.refresh_design_doc('db')
end
end
describe "#save_design_doc" do describe "#save_design_doc" do
it "should be proxied without args" do it "should be proxied without args" do
Cat.should_receive(:save_design_doc).with('database') Cat.should_receive(:save_design_doc).with('database')
@ -282,18 +241,22 @@ describe CouchRest::Model::Proxyable do
describe "#proxy_update" do describe "#proxy_update" do
it "should set returned doc fields" do it "should set returned doc fields" do
doc = mock(:Document) doc = mock(:Document)
doc.should_receive(:is_a?).with(Cat).and_return(true) doc.should_receive(:respond_to?).with(:database=).and_return(true)
doc.should_receive(:database=).with('database') doc.should_receive(:database=).with('database')
doc.should_receive(:respond_to?).with(:model_proxy=).and_return(true)
doc.should_receive(:model_proxy=).with(@obj) doc.should_receive(:model_proxy=).with(@obj)
doc.should_receive(:respond_to?).with('owner_name=').and_return(true)
doc.should_receive(:send).with('owner_name=', 'owner') doc.should_receive(:send).with('owner_name=', 'owner')
@obj.send(:proxy_update, doc).should eql(doc) @obj.send(:proxy_update, doc).should eql(doc)
end end
it "should not set anything if matching document not provided" do it "should not fail if some fields missing" do
doc = mock(:DocumentFoo) doc = mock(:Document)
doc.should_receive(:is_a?).with(Cat).and_return(false) doc.should_receive(:respond_to?).with(:database=).and_return(true)
doc.should_not_receive(:database=) doc.should_receive(:database=).with('database')
doc.should_receive(:respond_to?).with(:model_proxy=).and_return(false)
doc.should_not_receive(:model_proxy=) doc.should_not_receive(:model_proxy=)
doc.should_receive(:respond_to?).with('owner_name=').and_return(false)
doc.should_not_receive(:owner_name=) doc.should_not_receive(:owner_name=)
@obj.send(:proxy_update, doc).should eql(doc) @obj.send(:proxy_update, doc).should eql(doc)
end end
@ -309,15 +272,6 @@ describe CouchRest::Model::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
@ -355,7 +309,6 @@ describe CouchRest::Model::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.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,4 +1,8 @@
require "spec_helper" require File.expand_path("../../spec_helper", __FILE__)
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'
@ -67,14 +71,24 @@ describe "Subclassing a Model" do
end end
it "should have a design doc slug based on the subclass name" do it "should have a design doc slug based on the subclass name" do
Course.refresh_design_doc
OnlineCourse.design_doc_slug.should =~ /^OnlineCourse/ OnlineCourse.design_doc_slug.should =~ /^OnlineCourse/
end end
it "should have its own design_doc_fresh" do
Animal.refresh_design_doc
Dog.send(:design_doc_fresh, Dog.database).should_not == true
Dog.refresh_design_doc
Dog.send(:design_doc_fresh, Dog.database).should == true
end
it "should not add views to the parent's design_doc" do it "should not add views to the parent's design_doc" do
Course.design_doc['views'].keys.should_not include('by_url') Course.design_doc['views'].keys.should_not include('by_url')
end end
it "should not add the parent's views to its design doc" do it "should not add the parent's views to its design doc" do
Course.refresh_design_doc
OnlineCourse.refresh_design_doc
OnlineCourse.design_doc['views'].keys.should_not include('by_title') OnlineCourse.design_doc['views'].keys.should_not include('by_title')
end end

View file

@ -0,0 +1,83 @@
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')
# TODO Move validations from other specs to here
describe "Validations" do
describe "Uniqueness" do
before(:all) do
@objs = ['title 1', 'title 2', 'title 3'].map{|t| WithUniqueValidation.create(:title => t)}
end
it "should validate a new unique document" do
@obj = WithUniqueValidation.create(:title => 'title 4')
@obj.new?.should_not be_true
@obj.should be_valid
end
it "should not validate a non-unique document" do
@obj = WithUniqueValidation.create(:title => 'title 1')
@obj.should_not be_valid
@obj.errors[:title].should == ["has already been taken"]
end
it "should save already created document" do
@obj = @objs.first
@obj.save.should_not be_false
@obj.should be_valid
end
it "should allow own view to be specified" do
# validates_uniqueness_of :code, :view => 'all'
WithUniqueValidationView.create(:title => 'title 1', :code => '1234')
@obj = WithUniqueValidationView.new(:title => 'title 5', :code => '1234')
@obj.should_not be_valid
end
it "should raise an error if specified view does not exist" do
WithUniqueValidationView.validates_uniqueness_of :title, :view => 'fooobar'
@obj = WithUniqueValidationView.new(:title => 'title 2', :code => '12345')
lambda {
@obj.valid?
}.should raise_error
end
context "with a pre-defined view" do
it "should not try to create new view" do
@obj = @objs[1]
@obj.class.should_not_receive('view_by')
@obj.class.should_receive('has_view?').and_return(true)
@obj.class.should_receive('view').and_return({'rows' => [ ]})
@obj.valid?
end
end
context "with a proxy parameter" do
it "should be used" do
@obj = WithUniqueValidationProxy.new(:title => 'test 6')
proxy = @obj.should_receive('proxy').and_return(@obj.class)
@obj.valid?.should be_true
end
it "should allow specific view" do
@obj = WithUniqueValidationProxy.new(:title => 'test 7')
@obj.class.should_not_receive('view_by')
proxy = mock('Proxy')
@obj.should_receive('proxy').and_return(proxy)
proxy.should_receive('has_view?').and_return(true)
proxy.should_receive('view').and_return({'rows' => [ ]})
@obj.valid?
end
end
end
end

View file

@ -1,18 +1,19 @@
require "spec_helper" require File.expand_path("../../spec_helper", __FILE__)
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 CouchRest::Model::Views do describe "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!
@ -22,7 +23,7 @@ describe CouchRest::Model::Views do
it "should not alter original query" do it "should not alter original query" do
options = { :database => DB } options = { :database => DB }
view = Article.view('by_date', options) view = Article.view('by_date', options)
options[:database].should eql(DB) options[:database].should_not be_nil
end end
end end
@ -55,6 +56,35 @@ describe CouchRest::Model::Views do
written_at += 24 * 3600 written_at += 24 * 3600
end end
end end
it "should have a design doc" do
Article.design_doc["views"]["by_date"].should_not be_nil
end
it "should save the design doc" do
Article.by_date #rescue nil
doc = Article.database.get Article.design_doc.id
doc['views']['by_date'].should_not be_nil
end
it "should save design doc if a view changed" do
Article.by_date
orig = Article.stored_design_doc
orig['views']['by_date']['map'] = "function() { }"
Article.database.save_doc(orig)
rev = Article.stored_design_doc['_rev']
Article.req_design_doc_refresh # prepare for re-load
Article.by_date
orig = Article.stored_design_doc
orig['views']['by_date']['map'].should eql(Article.design_doc['views']['by_date']['map'])
orig['_rev'].should_not eql(rev)
end
it "should not save design doc if not changed" do
Article.by_date
orig = Article.stored_design_doc['_rev']
Article.req_design_doc_refresh
Article.by_date
Article.stored_design_doc['_rev'].should eql(orig)
end
it "should return the matching raw view result" do it "should return the matching raw view result" do
view = Article.by_date :raw => true view = Article.by_date :raw => true
view['rows'].length.should == 4 view['rows'].length.should == 4
@ -77,6 +107,7 @@ describe CouchRest::Model::Views do
Article.view_by :title Article.view_by :title
lambda{Article.by_title}.should_not raise_error lambda{Article.by_title}.should_not raise_error
end end
end end
describe "another model with a simple view" do describe "another model with a simple view" do
@ -174,21 +205,6 @@ describe CouchRest::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!
@ -209,7 +225,7 @@ describe CouchRest::Model::Views do
end end
end end
describe "a model class with database provided manually" do describe "a model class not tied to a database" do
before(:all) do before(:all) do
reset_test_db! reset_test_db!
@db = DB @db = DB
@ -224,6 +240,7 @@ describe CouchRest::Model::Views do
lambda{Unattached.all}.should raise_error lambda{Unattached.all}.should raise_error
end end
it "should query all" do it "should query all" do
# Unattached.cleanup_design_docs!(@db)
rs = Unattached.all :database => @db rs = Unattached.all :database => @db
rs.length.should == 4 rs.length.should == 4
end end
@ -281,6 +298,18 @@ describe CouchRest::Model::Views do
u.title.should == "aaa" u.title.should == "aaa"
end end
it "should barf on all_design_doc_versions if no database given" do
lambda{Unattached.all_design_doc_versions}.should raise_error
end
it "should be able to cleanup the db/bump the revision number" do
# if the previous specs were not run, the model_design_doc will be blank
Unattached.use_database DB
Unattached.view_by :questions
Unattached.by_questions(:database => @db)
original_revision = Unattached.model_design_doc(@db)['_rev']
Unattached.save_design_doc!(@db)
Unattached.model_design_doc(@db)['_rev'].should_not == original_revision
end
end end
describe "a model with a compound key view" do describe "a model with a compound key view" do
@ -348,7 +377,7 @@ describe CouchRest::Model::Views do
before(:each) do before(:each) do
reset_test_db! reset_test_db!
Article.by_date Article.by_date
@original_doc_rev = Article.stored_design_doc['_rev'] @original_doc_rev = Article.model_design_doc['_rev']
@design_docs = Article.database.documents :startkey => "_design/", :endkey => "_design/\u9999" @design_docs = Article.database.documents :startkey => "_design/", :endkey => "_design/\u9999"
end end
it "should not create a design doc on view definition" do it "should not create a design doc on view definition" do
@ -357,9 +386,10 @@ describe CouchRest::Model::Views do
newdocs["rows"].length.should == @design_docs["rows"].length newdocs["rows"].length.should == @design_docs["rows"].length
end end
it "should create a new version of the design document on view access" do it "should create a new version of the design document on view access" do
ddocs = Article.all_design_doc_versions["rows"].length
Article.view_by :updated_at Article.view_by :updated_at
Article.by_updated_at Article.by_updated_at
@original_doc_rev.should_not == Article.stored_design_doc['_rev'] @original_doc_rev.should_not == Article.model_design_doc['_rev']
Article.design_doc["views"].keys.should include("by_updated_at") Article.design_doc["views"].keys.should include("by_updated_at")
end end
end end

View file

@ -83,25 +83,11 @@ 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.slug model['important-field']
end end
property :slug
property :preset, :default => 'value' property :preset, :default => 'value'
property :has_no_default property :has_no_default
end end
@ -145,20 +131,11 @@ class WithUniqueValidationView < CouchRest::Model::Base
attr_accessor :code attr_accessor :code
unique_id :code unique_id :code
def code def code
@code self["_id"] ||= @code
end end
property :title property :title
validates_uniqueness_of :code, :view => 'all' validates_uniqueness_of :code, :view => 'all'
end end
class WithScopedUniqueValidation < CouchRest::Model::Base
use_database DB
property :parent_id
property :title
validates_uniqueness_of :title, :scope => :parent_id
end

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -22,7 +22,6 @@ 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

@ -1,5 +1,3 @@
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
@ -9,7 +7,7 @@ class Card < CouchRest::Model::Base
property :last_name, :alias => :family_name property :last_name, :alias => :family_name
property :read_only_value, :read_only => true property :read_only_value, :read_only => true
property :cast_alias, Person, :alias => :calias property :cast_alias, Person, :alias => :calias
property :fg_color, :default => '#000'
timestamps! timestamps!

View file

@ -1,6 +1,6 @@
class CatToy class CatToy < Hash
include CouchRest::Model::Embeddable include ::CouchRest::Model::CastedModel
property :name property :name
@ -17,7 +17,3 @@ 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 'question' require File.join(FIXTURE_PATH, 'more', 'question')
require 'person' require File.join(FIXTURE_PATH, 'more', 'person')
class Course < CouchRest::Model::Base class Course < CouchRest::Model::Base
use_database TEST_SERVER.default_database use_database TEST_SERVER.default_database

View file

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

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

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

View file

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

View file

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

View file

@ -1,16 +1,11 @@
$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" require "rspec" # Satisfies Autotest and anyone else not using the Rake tasks
require 'couchrest_model' require File.join(File.dirname(__FILE__), '..','lib','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')
@ -21,6 +16,15 @@ 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
DB
end
RSpec.configure do |config| RSpec.configure do |config|
config.before(:all) { reset_test_db! } config.before(:all) { reset_test_db! }
@ -33,21 +37,6 @@ 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

@ -1,30 +0,0 @@
# 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,148 +0,0 @@
# 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,77 +0,0 @@
# encoding: utf-8
require File.expand_path('../../../spec_helper', __FILE__)
describe "Time Parsing core extension" do
describe "Time" do
it "should respond to .parse_iso8601" do
Time.respond_to?("parse_iso8601").should be_true
end
describe ".parse_iso8601" do
describe "parsing" do
before :each do
# Time.parse should not be called for these tests!
Time.stub!(:parse).and_return(nil)
end
it "should parse JSON time" do
txt = "2011-04-01T19:05:30Z"
Time.parse_iso8601(txt).should eql(Time.utc(2011, 04, 01, 19, 05, 30))
end
it "should parse JSON time as UTC without Z" do
txt = "2011-04-01T19:05:30"
Time.parse_iso8601(txt).should eql(Time.utc(2011, 04, 01, 19, 05, 30))
end
it "should parse basic time as UTC" do
txt = "2011-04-01 19:05:30"
Time.parse_iso8601(txt).should eql(Time.utc(2011, 04, 01, 19, 05, 30))
end
it "should parse JSON time with zone" do
txt = "2011-04-01T19:05:30 +02:00"
Time.parse_iso8601(txt).should eql(Time.new(2011, 04, 01, 19, 05, 30, "+02:00"))
end
it "should parse JSON time with zone 2" do
txt = "2011-04-01T19:05:30-0200"
Time.parse_iso8601(txt).should eql(Time.new(2011, 04, 01, 19, 05, 30, "-02:00"))
end
it "should parse dodgy time with zone" do
txt = "2011-04-01 19:05:30 +0200"
Time.parse_iso8601(txt).should eql(Time.new(2011, 04, 01, 19, 05, 30, "+02:00"))
end
it "should parse dodgy time with zone 2" do
txt = "2011-04-01 19:05:30+0230"
Time.parse_iso8601(txt).should eql(Time.new(2011, 04, 01, 19, 05, 30, "+02:30"))
end
it "should parse dodgy time with zone 3" do
txt = "2011-04-01 19:05:30 0230"
Time.parse_iso8601(txt).should eql(Time.new(2011, 04, 01, 19, 05, 30, "+02:30"))
end
end
describe "resorting back to normal parse" do
before :each do
Time.should_receive(:parse)
end
it "should work with weird time" do
txt = "16/07/1981 05:04:00"
Time.parse_iso8601(txt)
end
end
end
end
end

View file

@ -1,241 +0,0 @@
# encoding: utf-8
require 'spec_helper'
describe CouchRest::Model::DesignDoc do
before :all do
reset_test_db!
end
describe "CouchRest Extension" do
it "should have created a checksum! method" do
::CouchRest::Design.new.should respond_to(:checksum!)
end
it "should calculate a consistent checksum for model" do
WithTemplateAndUniqueID.design_doc.checksum!.should eql('caa2b4c27abb82b4e37421de76d96ffc')
end
it "should calculate checksum for complex model" do
Article.design_doc.checksum!.should eql('70dff8caea143bf40fad09adf0701104')
end
it "should cache the generated checksum value" do
Article.design_doc.checksum!
Article.design_doc['couchrest-hash'].should_not be_blank
end
end
describe "class methods" do
describe ".design_doc" do
it "should provide Design document" do
Article.design_doc.should be_a(::CouchRest::Design)
end
end
describe ".design_doc_id" do
it "should provide a reasonable id" do
Article.design_doc_id.should eql("_design/Article")
end
end
describe ".design_doc_slug" do
it "should provide slug part of design doc" do
Article.design_doc_slug.should eql('Article')
end
end
describe ".design_doc_uri" do
it "should provide complete url" do
Article.design_doc_uri.should eql("#{COUCHHOST}/#{TESTDB}/_design/Article")
end
it "should provide complete url for new DB" do
db = mock("Database")
db.should_receive(:root).and_return('db')
Article.design_doc_uri(db).should eql("db/_design/Article")
end
end
describe ".stored_design_doc" do
it "should load a stored design from the database" do
Article.by_date
Article.stored_design_doc['_rev'].should_not be_blank
end
it "should return nil if not already stored" do
WithDefaultValues.stored_design_doc.should be_nil
end
end
describe ".save_design_doc" do
it "should call up the design updater" do
Article.should_receive(:update_design_doc).with('db', false)
Article.save_design_doc('db')
end
end
describe ".save_design_doc!" do
it "should call save_design_doc with force" do
Article.should_receive(:save_design_doc).with('db', true)
Article.save_design_doc!('db')
end
end
end
describe "basics" do
before :all do
reset_test_db!
end
it "should have been instantiated with views" do
d = Article.design_doc
d['views']['all']['map'].should include('Article')
end
it "should not have been saved yet" do
lambda { Article.database.get(Article.design_doc.id) }.should raise_error(RestClient::ResourceNotFound)
end
describe "after requesting a view" do
before :each do
Article.all
end
it "should have saved the design doc after view request" do
Article.database.get(Article.design_doc.id).should_not be_nil
end
end
describe "model with simple views" do
before(:all) do
Article.all.map{|a| a.destroy(true)}
Article.database.bulk_delete
written_at = Time.now - 24 * 3600 * 7
@titles = ["this and that", "also interesting", "more fun", "some junk"]
@titles.each do |title|
a = Article.new(:title => title)
a.date = written_at
a.save
written_at += 24 * 3600
end
end
it "will send request for the saved design doc on view request" do
reset_test_db!
Article.should_receive(:stored_design_doc).and_return(nil)
Article.by_date
end
it "should have generated a design doc" do
Article.design_doc["views"]["by_date"].should_not be_nil
end
it "should save the design doc when view requested" do
Article.by_date
doc = Article.database.get Article.design_doc.id
doc['views']['by_date'].should_not be_nil
end
it "should save design doc if a view changed" do
Article.by_date
orig = Article.stored_design_doc
design = Article.design_doc
view = design['views']['by_date']['map']
design['views']['by_date']['map'] = view + ' ' # little bit of white space
Article.by_date
Article.stored_design_doc['_rev'].should_not eql(orig['_rev'])
orig['views']['by_date']['map'].should_not eql(Article.design_doc['views']['by_date']['map'])
end
it "should not save design doc if not changed" do
Article.by_date
orig = Article.stored_design_doc['_rev']
Article.by_date
Article.stored_design_doc['_rev'].should eql(orig)
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
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);
}"}}
DB.save_doc doc
eval <<-KLASS
class ::#{class_name} < CouchRest::Model::Base
use_database DB
self.auto_update_design_doc = false
design do
view :by_name
end
property :name, String
end
KLASS
class_name.constantize
}
it "will not update stored design doc if view changed" do
model_class.by_name
orig = model_class.stored_design_doc
design = model_class.design_doc
view = design['views']['by_name']['map']
design['views']['by_name']['map'] = view + ' '
model_class.by_name
model_class.stored_design_doc['_rev'].should eql(orig['_rev'])
end
it "will update stored design if forced" do
model_class.by_name
orig = model_class.stored_design_doc
design = model_class.design_doc
view = design['views']['by_name']['map']
design['views']['by_name']['map'] = view + ' '
model_class.save_design_doc!
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
describe "lazily refreshing the design document" do
before(:all) do
@db = reset_test_db!
WithTemplateAndUniqueID.new('slug' => '1').save
end
it "should not save the design doc twice" do
WithTemplateAndUniqueID.all
rev = WithTemplateAndUniqueID.design_doc['_rev']
WithTemplateAndUniqueID.design_doc['_rev'].should eql(rev)
end
end
end

View file

@ -1,436 +0,0 @@
require "spec_helper"
class WithCastedModelMixin
include CouchRest::Model::CastedModel
property :name
property :details, Object, :default => {}
property :casted_attribute, WithCastedModelMixin
end
class DirtyModel < CouchRest::Model::Base
use_database DB
property :casted_attribute, WithCastedModelMixin
property :title, :default => 'Sample Title'
property :details, Object, :default => { 'color' => 'blue' }
property :keywords, [String], :default => ['default-keyword']
property :sub_models do
property :title
end
end
class DirtyUniqueIdModel < CouchRest::Model::Base
use_database DB
attr_accessor :code
unique_id :code
property :title, String, :default => "Sample Title"
timestamps!
def code; self['_id'] || @code; end
end
describe "Dirty" do
describe "changes" do
it "should return changes on an attribute" do
@card = Card.new(:first_name => "matt")
@card.first_name = "andrew"
@card.first_name_changed?.should be_true
@card.changes.should == { "first_name" => ["matt", "andrew"] }
end
end
describe "save" do
it "should not save unchanged records" do
card_id = Card.create!(:first_name => "matt").id
@card = Card.find(card_id)
@card.database.should_not_receive(:save_doc)
@card.save
end
it "should save changed records" do
card_id = Card.create!(:first_name => "matt").id
@card = Card.find(card_id)
@card.first_name = "andrew"
@card.database.should_receive(:save_doc).and_return({"ok" => true})
@card.save
end
end
describe "changed?" do
# match activerecord behaviour
it "should report no changes on a new object with no attributes set" do
@card = Card.new
@card.changed?.should be_false
end
it "should report no changes on a hash property with a default value" do
@obj = DirtyModel.new
@obj.details.changed?.should be_false
end
# match activerecord behaviour
it "should report changes on a new object with attributes set" do
@card = Card.new(:first_name => "matt")
@card.changed?.should be_true
end
it "should report no changes on new object with 'unique_id' set" do
@obj = DirtyUniqueIdModel.new
@obj.changed?.should be_false
@obj.changes.should be_empty
end
it "should report no changes on objects fetched from the database" do
card_id = Card.create!(:first_name => "matt").id
@card = Card.find(card_id)
@card.changed?.should be_false
end
it "should report changes if the record is modified" do
@card = Card.new
@card.first_name = "andrew"
@card.changed?.should be_true
@card.first_name_changed?.should be_true
end
it "should report no changes for unmodified records" do
card_id = Card.create!(:first_name => "matt").id
@card = Card.find(card_id)
@card.first_name = "matt"
@card.changed?.should be_false
@card.first_name_changed?.should be_false
end
it "should report no changes after a new record has been saved" do
@card = Card.new(:first_name => "matt")
@card.save!
@card.changed?.should be_false
end
it "should report no changes after a record has been saved" do
card_id = Card.create!(:first_name => "matt").id
@card = Card.find(card_id)
@card.first_name = "andrew"
@card.save!
@card.changed?.should be_false
end
# test changing list properties
it "should report changes if a list property is modified" do
cat_id = Cat.create!(:name => "Felix", :toys => [{:name => "Mouse"}]).id
@cat = Cat.find(cat_id)
@cat.toys = [{:name => "Feather"}]
@cat.changed?.should be_true
end
it "should report no changes if a list property is unmodified" do
cat_id = Cat.create!(:name => "Felix", :toys => [{:name => "Mouse"}]).id
@cat = Cat.find(cat_id)
@cat.toys = [{:name => "Mouse"}] # same as original list
@cat.changed?.should be_false
end
# attachments
it "should report changes if an attachment is added" do
cat_id = Cat.create!(:name => "Felix", :toys => [{:name => "Mouse"}]).id
@file = File.open(FIXTURE_PATH + '/attachments/test.html')
@cat = Cat.find(cat_id)
@cat.create_attachment(:file => @file, :name => "my_attachment")
@cat.changed?.should be_true
end
it "should report changes if an attachment is deleted" do
@cat = Cat.create!(:name => "Felix", :toys => [{:name => "Mouse"}])
@file = File.open(FIXTURE_PATH + '/attachments/test.html')
@attachment_name = "my_attachment"
@cat.create_attachment(:file => @file, :name => @attachment_name)
@cat.save
@cat = Cat.find(@cat.id)
@cat.delete_attachment(@attachment_name)
@cat.changed?.should be_true
end
# casted models
it "should report changes to casted models" do
@cat = Cat.create!(:name => "Felix", :favorite_toy => { :name => "Mouse" })
@cat = Cat.find(@cat.id)
@cat.favorite_toy.name = 'Feather'
@cat.changed?.should be_true
end
it "should report changes to casted model in array" do
@obj = Cat.create!(:name => 'felix', :toys => [{:name => "Catnip"}])
@obj = Cat.get(@obj.id)
@obj.toys.first.name.should eql('Catnip')
@obj.toys.first.changed?.should be_false
@obj.changed?.should be_false
@obj.toys.first.name = "Super Catnip"
@obj.toys.first.changed?.should be_true
@obj.changed?.should be_true
end
it "should report changes to anonymous casted models in array" do
@obj = DirtyModel.create!(:sub_models => [{:title => "Sample"}])
@obj = DirtyModel.get(@obj.id)
@obj.sub_models.first.title.should eql("Sample")
@obj.sub_models.first.changed?.should be_false
@obj.changed?.should be_false
@obj.sub_models.first.title = "Another Sample"
@obj.sub_models.first.changed?.should be_true
@obj.changed?.should be_true
end
# casted arrays
def test_casted_array(change_expected)
obj = DirtyModel.create!
obj = DirtyModel.get(obj.id)
array = obj.keywords
yield array, obj
if change_expected
obj.changed?.should be_true
else
obj.changed?.should be_false
end
end
def should_change_array
test_casted_array(true) { |a,b| yield a,b }
end
def should_not_change_array
test_casted_array(false) { |a,b| yield a,b }
end
it "should report changes if an array index is modified" do
should_change_array do |array, obj|
array[0] = "keyword"
end
end
it "should report no changes if an array index is unmodified" do
should_not_change_array do |array, obj|
array[0] = array[0]
end
end
it "should report changes if an array is appended with <<" do
should_change_array do |array, obj|
array << 'keyword'
end
end
it "should report changes if an array is popped" do
should_change_array do |array, obj|
array.pop
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
should_not_change_array do |array, obj|
array.clear
obj.save! # clears changes
array.pop
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
should_change_array do |array, obj|
array.push("keyword")
end
end
it "should report changes if an array is shifted" do
should_change_array do |array, obj|
array.shift
end
end
it "should report no changes if an empty array is shifted" do
should_not_change_array do |array, obj|
array.clear
obj.save! # clears changes
array.shift
end
end
it "should report changes if an array is unshifted" do
should_change_array do |array, obj|
array.unshift("keyword")
end
end
it "should report changes if an array is cleared" do
should_change_array do |array, obj|
array.clear
end
end
# Object, {} (casted hash)
def test_casted_hash(change_expected)
obj = DirtyModel.create!
obj = DirtyModel.get(obj.id)
hash = obj.details
yield hash, obj
if change_expected
obj.changed?.should be_true
else
obj.changed?.should be_false
end
end
def should_change_hash
test_casted_hash(true) { |a,b| yield a,b }
end
def should_not_change_hash
test_casted_hash(false) { |a,b| yield a,b }
end
it "should report changes if a hash is modified" do
should_change_hash do |hash, obj|
hash['color'] = 'orange'
end
end
it "should report no changes if a hash is unmodified" do
should_not_change_hash do |hash, obj|
hash['color'] = hash['color']
end
end
it "should report changes when deleting from a hash" do
should_change_hash do |hash, obj|
hash.delete('color')
end
end
it "should report no changes when deleting a non existent key from a hash" do
should_not_change_hash do |hash, obj|
hash.delete('non-existent-key')
end
end
it "should report changes when clearing a hash" do
should_change_hash do |hash, obj|
hash.clear
end
end
it "should report changes when merging changes to a hash" do
should_change_hash do |hash, obj|
hash.merge!('foo' => 'bar')
end
end
it "should report no changes when merging no changes to a hash" do
should_not_change_hash do |hash, obj|
hash.merge!('color' => hash['color'])
end
end
it "should report changes when replacing hash content" do
should_change_hash do |hash, obj|
hash.replace('foo' => 'bar')
end
end
it "should report no changes when replacing hash content with same content" do
should_not_change_hash do |hash, obj|
hash.replace(hash)
end
end
it "should report changes when removing records with delete_if" do
should_change_hash do |hash, obj|
hash.delete_if { true }
end
end
it "should report no changes when removing no records with delete_if" do
should_not_change_hash do |hash, obj|
hash.delete_if { false }
end
end
if {}.respond_to?(:keep_if)
it "should report changes when removing records with keep_if" do
should_change_hash do |hash, obj|
hash.keep_if { false }
end
end
it "should report no changes when removing no records with keep_if" do
should_not_change_hash do |hash, obj|
hash.keep_if { true }
end
end
end
end
end

View file

@ -1,33 +0,0 @@
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,481 +0,0 @@
# encoding: utf-8
require 'spec_helper'
describe CouchRest::Model::Property do
before(:each) do
reset_test_db!
@card = Card.new(:first_name => "matt")
end
it "should be accessible from the object" do
@card.properties.should be_an_instance_of(Array)
@card.properties.map{|p| p.name}.should include("first_name")
end
it "should list object properties with values" do
@card.properties_with_values.should be_an_instance_of(Hash)
@card.properties_with_values["first_name"].should == "matt"
end
it "should let you access a property value (getter)" do
@card.first_name.should == "matt"
end
it "should let you set a property value (setter)" do
@card.last_name = "Aimonetti"
@card.last_name.should == "Aimonetti"
end
it "should not let you set a property value if it's read only" do
lambda{@card.read_only_value = "test"}.should raise_error
end
it "should let you use an alias for an attribute" do
@card.last_name = "Aimonetti"
@card.family_name.should == "Aimonetti"
@card.family_name.should == @card.last_name
end
it "should let you use an alias for a casted attribute" do
@card.cast_alias = Person.new(:name => ["Aimonetti"])
@card.cast_alias.name.should == ["Aimonetti"]
@card.calias.name.should == ["Aimonetti"]
card = Card.new(:first_name => "matt", :cast_alias => {:name => ["Aimonetti"]})
card.cast_alias.name.should == ["Aimonetti"]
card.calias.name.should == ["Aimonetti"]
end
it "should raise error if property name coincides with model type key" do
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
it "should be auto timestamped" do
@card.created_at.should be_nil
@card.updated_at.should be_nil
@card.save.should be_true
@card.created_at.should_not be_nil
@card.updated_at.should_not be_nil
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
it "should let you use read_attribute method" do
@card.last_name = "Aimonetti"
@card.read_attribute(:last_name).should eql('Aimonetti')
@card.read_attribute('last_name').should eql('Aimonetti')
last_name_prop = @card.properties.find{|p| p.name == 'last_name'}
@card.read_attribute(last_name_prop).should eql('Aimonetti')
end
it 'should raise an error if the property does not exist' do
expect { @card.read_attribute(:this_property_should_not_exist) }.to raise_error(ArgumentError)
end
end
describe '#write_attribute' do
it "should let you use write_attribute method" do
@card.write_attribute(:last_name, 'Aimonetti 1')
@card.last_name.should eql('Aimonetti 1')
@card.write_attribute('last_name', 'Aimonetti 2')
@card.last_name.should eql('Aimonetti 2')
last_name_prop = @card.properties.find{|p| p.name == 'last_name'}
@card.write_attribute(last_name_prop, 'Aimonetti 3')
@card.last_name.should eql('Aimonetti 3')
end
it 'should raise an error if the property does not exist' do
expect { @card.write_attribute(:this_property_should_not_exist, 823) }.to raise_error(ArgumentError)
end
it "should let you use write_attribute on readonly properties" do
lambda {
@card.read_only_value = "foo"
}.should raise_error
@card.write_attribute(:read_only_value, "foo")
@card.read_only_value.should == 'foo'
end
it "should cast via write_attribute" do
@card.write_attribute(:cast_alias, {:name => ["Sam", "Lown"]})
@card.cast_alias.class.should eql(Person)
@card.cast_alias.name.last.should eql("Lown")
end
it "should not cast via write_attribute if property not casted" do
@card.write_attribute(:first_name, {:name => "Sam"})
@card.first_name.class.should eql(Hash)
@card.first_name[:name].should eql("Sam")
end
end
describe "mass updating attributes without property" do
describe "when mass_assign_any_attribute false" do
it "should not allow them to be set" do
@card.attributes = {:test => 'fooobar'}
@card['test'].should be_nil
end
end
describe "when mass_assign_any_attribute true" do
before(:each) do
# dup Card class so that no other tests are effected
card_class = Card.dup
card_class.class_eval do
mass_assign_any_attribute true
end
@card = card_class.new(:first_name => 'Sam')
end
it 'should allow them to be updated' do
@card.attributes = {:test => 'fooobar'}
@card['test'].should eql('fooobar')
end
end
end
describe "mass assignment protection" do
it "should not store protected attribute using mass assignment" do
cat_toy = CatToy.new(:name => "Zorro")
cat = Cat.create(:name => "Helena", :toys => [cat_toy], :favorite_toy => cat_toy, :number => 1)
cat.number.should be_nil
cat.number = 1
cat.save
cat.number.should == 1
end
it "should not store protected attribute when 'declare accessible poperties, assume all the rest are protected'" do
user = User.create(:name => "Marcos Tapajós", :admin => true)
user.admin.should be_nil
end
it "should not store protected attribute when 'declare protected properties, assume all the rest are accessible'" do
user = SpecialUser.create(:name => "Marcos Tapajós", :admin => true)
user.admin.should be_nil
end
end
describe "validation" do
before(:each) do
@invoice = Invoice.new(:client_name => "matt", :employee_name => "Chris", :location => "San Diego, CA")
end
it "should be able to be validated" do
@card.valid?.should == true
end
it "should let you validate the presence of an attribute" do
@card.first_name = nil
@card.should_not be_valid
@card.errors.should_not be_empty
@card.errors[:first_name].should == ["can't be blank"]
end
it "should let you look up errors for a field by a string name" do
@card.first_name = nil
@card.should_not be_valid
@card.errors['first_name'].should == ["can't be blank"]
end
it "should validate the presence of 2 attributes" do
@invoice.clear
@invoice.should_not be_valid
@invoice.errors.should_not be_empty
@invoice.errors[:client_name].should == ["can't be blank"]
@invoice.errors[:employee_name].should_not be_empty
end
it "should let you set an error message" do
@invoice.location = nil
@invoice.valid?
@invoice.errors[:location].should == ["Hey stupid!, you forgot the location"]
end
it "should validate before saving" do
@invoice.location = nil
@invoice.should_not be_valid
@invoice.save.should be_false
@invoice.should be_new
end
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
before(:each) do
@course = Course.new :title => 'Test Course'
end
it "should allow attribute to be set from an array of objects" do
@course.questions = [Question.new(:q => "works?"), Question.new(:q => "Meaning of Life?")]
@course.questions.length.should eql(2)
end
it "should allow attribute to be set from an array of hashes" do
@course.questions = [{:q => "works?"}, {:q => "Meaning of Life?"}]
@course.questions.length.should eql(2)
@course.questions.last.q.should eql("Meaning of Life?")
@course.questions.last.class.should eql(Question) # typecasting
end
it "should allow attribute to be set from hash with ordered keys and objects" do
@course.questions = { '0' => Question.new(:q => "Test1"), '1' => Question.new(:q => 'Test2') }
@course.questions.length.should eql(2)
@course.questions.last.q.should eql('Test2')
@course.questions.last.class.should eql(Question)
end
it "should allow attribute to be set from hash with ordered keys and sub-hashes" do
@course.questions = { '10' => {:q => 'Test10'}, '0' => {:q => "Test1"}, '1' => {:q => 'Test2'} }
@course.questions.length.should eql(3)
@course.questions.last.q.should eql('Test10')
@course.questions.last.class.should eql(Question)
end
it "should allow attribute to be set from hash with ordered keys and HashWithIndifferentAccess" do
# This is similar to what you'd find in an HTML POST parameters
hash = HashWithIndifferentAccess.new({ '0' => {:q => "Test1"}, '1' => {:q => 'Test2'} })
@course.questions = hash
@course.questions.length.should eql(2)
@course.questions.last.q.should eql('Test2')
@course.questions.last.class.should eql(Question)
end
it "should raise an error if attempting to set single value for array type" do
lambda {
@course.questions = Question.new(:q => 'test1')
}.should raise_error(/Expecting an array/)
end
end
describe "a casted model retrieved from the database" do
before(:each) do
reset_test_db!
@cat = Cat.new(:name => 'Stimpy')
@cat.favorite_toy = CatToy.new(:name => 'Stinky')
@cat.toys << CatToy.new(:name => 'Feather')
@cat.toys << CatToy.new(:name => 'Mouse')
@cat.save
@cat = Cat.get(@cat.id)
end
describe "as a casted property" do
it "should already be casted_by its parent" do
@cat.favorite_toy.casted_by.should === @cat
end
end
describe "from a casted collection" do
it "should already be casted_by its parent" do
@cat.toys[0].casted_by.should === @cat
@cat.toys[1].casted_by.should === @cat
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
it "should provide name as string" do
property = CouchRest::Model::Property.new(:test, String)
property.name.should eql('test')
property.to_s.should eql('test')
end
it "should provide class from type" do
property = CouchRest::Model::Property.new(:test, String)
property.type_class.should eql(String)
end
it "should provide base class from type in array" do
property = CouchRest::Model::Property.new(:test, [String])
property.type_class.should eql(String)
end
it "should raise error if type as string requested" do
lambda {
property = CouchRest::Model::Property.new(:test, 'String')
}.should raise_error
end
it "should leave type nil and return class as nil also" do
property = CouchRest::Model::Property.new(:test, nil)
property.type.should be_nil
property.type_class.should be_nil
end
it "should convert empty type array to [Object]" do
property = CouchRest::Model::Property.new(:test, [])
property.type_class.should eql(Object)
end
it "should set init method option or leave as 'new'" do
# (bad example! Time already typecast)
property = CouchRest::Model::Property.new(:test, Time)
property.init_method.should eql('new')
property = CouchRest::Model::Property.new(:test, Time, :init_method => 'parse')
property.init_method.should eql('parse')
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.
describe "casting" do
it "should cast a value" do
property = CouchRest::Model::Property.new(:test, Date)
parent = mock("FooObject")
property.cast(parent, "2010-06-16").should eql(Date.new(2010, 6, 16))
property.cast_value(parent, "2010-06-16").should eql(Date.new(2010, 6, 16))
end
it "should cast an array of values" do
property = CouchRest::Model::Property.new(:test, [Date])
parent = mock("FooObject")
property.cast(parent, ["2010-06-01", "2010-06-02"]).should eql([Date.new(2010, 6, 1), Date.new(2010, 6, 2)])
end
it "should set a CastedArray on array of Objects" do
property = CouchRest::Model::Property.new(:test, [Object])
parent = mock("FooObject")
property.cast(parent, ["2010-06-01", "2010-06-02"]).class.should eql(CouchRest::Model::CastedArray)
end
it "should set a CastedArray on array of Strings" do
property = CouchRest::Model::Property.new(:test, [String])
parent = mock("FooObject")
property.cast(parent, ["2010-06-01", "2010-06-02"]).class.should eql(CouchRest::Model::CastedArray)
end
it "should allow instantion of model via CastedArray#build" do
property = CouchRest::Model::Property.new(:dates, [Date])
parent = Article.new
ary = property.cast(parent, [])
obj = ary.build(2011, 05, 21)
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
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
property = CouchRest::Model::Property.new(:test, [Object])
parent = mock("FooObject")
property.cast(parent, ["2010-06-01", "2010-06-02"]).casted_by.should eql(parent)
end
it "should set casted_by on new value" do
property = CouchRest::Model::Property.new(:test, CatToy)
parent = mock("CatObject")
cast = property.cast(parent, {:name => 'catnip'})
cast.casted_by.should eql(parent)
end
end
end

View file

@ -1,521 +0,0 @@
# encoding: utf-8
require 'spec_helper'
describe "Type Casting" do
before(:each) do
@course = Course.new(:title => 'Relaxation')
end
describe "when value is nil" do
it "leaves the value unchanged" do
@course.title = nil
@course['title'].should == nil
end
end
describe "when type primitive is an Object" do
it "it should not cast given value" do
@course.participants = [{}, 'q', 1]
@course['participants'].should == [{}, 'q', 1]
end
it "should cast started_on to Date" do
@course.started_on = Date.today
@course['started_on'].should be_an_instance_of(Date)
end
end
describe "when type primitive is a String" do
it "keeps string value unchanged" do
value = "1.0"
@course.title = value
@course['title'].should equal(value)
end
it "it casts to string representation of the value" do
@course.title = 1.0
@course['title'].should eql("1.0")
end
end
describe 'when type primitive is a Float' do
it 'returns same value if a float' do
value = 24.0
@course.estimate = value
@course['estimate'].should equal(value)
end
it 'returns float representation of a zero string integer' do
@course.estimate = '0'
@course['estimate'].should eql(0.0)
end
it 'returns float representation of a positive string integer' do
@course.estimate = '24'
@course['estimate'].should eql(24.0)
end
it 'returns float representation of a negative string integer' do
@course.estimate = '-24'
@course['estimate'].should eql(-24.0)
end
it 'returns float representation of a zero string float' do
@course.estimate = '0.0'
@course['estimate'].should eql(0.0)
end
it 'returns float representation of a positive string float' do
@course.estimate = '24.35'
@course['estimate'].should eql(24.35)
end
it 'returns float representation of a negative string float' do
@course.estimate = '-24.35'
@course['estimate'].should eql(-24.35)
end
it 'returns float representation of a zero string float, with no leading digits' do
@course.estimate = '.0'
@course['estimate'].should eql(0.0)
end
it 'returns float representation of a positive string float, with no leading digits' do
@course.estimate = '.41'
@course['estimate'].should eql(0.41)
end
it 'returns float representation of a zero integer' do
@course.estimate = 0
@course['estimate'].should eql(0.0)
end
it 'returns float representation of a positive integer' do
@course.estimate = 24
@course['estimate'].should eql(24.0)
end
it 'returns float representation of a negative integer' do
@course.estimate = -24
@course['estimate'].should eql(-24.0)
end
it 'returns float representation of a zero decimal' do
@course.estimate = BigDecimal('0.0')
@course['estimate'].should eql(0.0)
end
it 'returns float representation of a positive decimal' do
@course.estimate = BigDecimal('24.35')
@course['estimate'].should eql(24.35)
end
it 'returns float representation of a negative decimal' do
@course.estimate = BigDecimal('-24.35')
@course['estimate'].should eql(-24.35)
end
it 'return float of a number with commas instead of points for decimals' do
@course.estimate = '23,35'
@course['estimate'].should eql(23.35)
end
it "should handle numbers with commas and points" do
@course.estimate = '1,234.00'
@course.estimate.should eql(1234.00)
end
it "should handle a mis-match of commas and points and maintain the last one" do
@course.estimate = "1,232.434.123,323"
@course.estimate.should eql(1232434123.323)
end
it "should handle numbers with whitespace" do
@course.estimate = " 24.35 "
@course.estimate.should eql(24.35)
end
[ Object.new, true, '00.0', '0.', '-.0', 'string' ].each do |value|
it "does not typecast non-numeric value #{value.inspect}" do
@course.estimate = value
@course['estimate'].should equal(value)
end
end
end
describe 'when type primitive is a Integer' do
it 'returns same value if an integer' do
value = 24
@course.hours = value
@course['hours'].should equal(value)
end
it 'returns integer representation of a zero string integer' do
@course.hours = '0'
@course['hours'].should eql(0)
end
it 'returns integer representation of a positive string integer' do
@course.hours = '24'
@course['hours'].should eql(24)
end
it 'returns integer representation of a negative string integer' do
@course.hours = '-24'
@course['hours'].should eql(-24)
end
it 'returns integer representation of a zero string float' do
@course.hours = '0.0'
@course['hours'].should eql(0)
end
it 'returns integer representation of a positive string float' do
@course.hours = '24.35'
@course['hours'].should eql(24)
end
it 'returns integer representation of a negative string float' do
@course.hours = '-24.35'
@course['hours'].should eql(-24)
end
it 'returns integer representation of a zero string float, with no leading digits' do
@course.hours = '.0'
@course['hours'].should eql(0)
end
it 'returns integer representation of a positive string float, with no leading digits' do
@course.hours = '.41'
@course['hours'].should eql(0)
end
it 'returns integer representation of a zero float' do
@course.hours = 0.0
@course['hours'].should eql(0)
end
it 'returns integer representation of a positive float' do
@course.hours = 24.35
@course['hours'].should eql(24)
end
it 'returns integer representation of a negative float' do
@course.hours = -24.35
@course['hours'].should eql(-24)
end
it 'returns integer representation of a zero decimal' do
@course.hours = '0.0'
@course['hours'].should eql(0)
end
it 'returns integer representation of a positive decimal' do
@course.hours = '24.35'
@course['hours'].should eql(24)
end
it 'returns integer representation of a negative decimal' do
@course.hours = '-24.35'
@course['hours'].should eql(-24)
end
it "should handle numbers with whitespace" do
@course.hours = " 24 "
@course['hours'].should eql(24)
end
[ Object.new, true, '00.0', '0.', '-.0', 'string' ].each do |value|
it "does not typecast non-numeric value #{value.inspect}" do
@course.hours = value
@course['hours'].should equal(value)
end
end
end
describe 'when type primitive is a BigDecimal' do
it 'returns same value if a decimal' do
value = BigDecimal('24.0')
@course.profit = value
@course['profit'].should equal(value)
end
it 'returns decimal representation of a zero string integer' do
@course.profit = '0'
@course['profit'].should eql(BigDecimal('0.0'))
end
it 'returns decimal representation of a positive string integer' do
@course.profit = '24'
@course['profit'].should eql(BigDecimal('24.0'))
end
it 'returns decimal representation of a negative string integer' do
@course.profit = '-24'
@course['profit'].should eql(BigDecimal('-24.0'))
end
it 'returns decimal representation of a zero string float' do
@course.profit = '0.0'
@course['profit'].should eql(BigDecimal('0.0'))
end
it 'returns decimal representation of a positive string float' do
@course.profit = '24.35'
@course['profit'].should eql(BigDecimal('24.35'))
end
it 'returns decimal representation of a negative string float' do
@course.profit = '-24.35'
@course['profit'].should eql(BigDecimal('-24.35'))
end
it 'returns decimal representation of a zero string float, with no leading digits' do
@course.profit = '.0'
@course['profit'].should eql(BigDecimal('0.0'))
end
it 'returns decimal representation of a positive string float, with no leading digits' do
@course.profit = '.41'
@course['profit'].should eql(BigDecimal('0.41'))
end
it 'returns decimal representation of a zero integer' do
@course.profit = 0
@course['profit'].should eql(BigDecimal('0.0'))
end
it 'returns decimal representation of a positive integer' do
@course.profit = 24
@course['profit'].should eql(BigDecimal('24.0'))
end
it 'returns decimal representation of a negative integer' do
@course.profit = -24
@course['profit'].should eql(BigDecimal('-24.0'))
end
it 'returns decimal representation of a zero float' do
@course.profit = 0.0
@course['profit'].should eql(BigDecimal('0.0'))
end
it 'returns decimal representation of a positive float' do
@course.profit = 24.35
@course['profit'].should eql(BigDecimal('24.35'))
end
it 'returns decimal representation of a negative float' do
@course.profit = -24.35
@course['profit'].should eql(BigDecimal('-24.35'))
end
it "should handle numbers with whitespace" do
@course.profit = " 24.35 "
@course['profit'].should eql(BigDecimal('24.35'))
end
[ Object.new, true, '00.0', '0.', '-.0', 'string' ].each do |value|
it "does not typecast non-numeric value #{value.inspect}" do
@course.profit = value
@course['profit'].should equal(value)
end
end
end
describe 'when type primitive is a DateTime' do
describe 'and value given as a hash with keys like :year, :month, etc' do
it 'builds a DateTime instance from hash values' do
@course.updated_at = {
:year => '2006',
:month => '11',
:day => '23',
:hour => '12',
:min => '0',
:sec => '0'
}
result = @course['updated_at']
result.should be_kind_of(DateTime)
result.year.should eql(2006)
result.month.should eql(11)
result.day.should eql(23)
result.hour.should eql(12)
result.min.should eql(0)
result.sec.should eql(0)
end
end
describe 'and value is a string' do
it 'parses the string' do
@course.updated_at = 'Dec, 2006'
@course['updated_at'].month.should == 12
end
end
it 'does not typecast non-datetime values' do
@course.updated_at = 'not-datetime'
@course['updated_at'].should eql('not-datetime')
end
end
describe 'when type primitive is a Date' do
describe 'and value given as a hash with keys like :year, :month, etc' do
it 'builds a Date instance from hash values' do
@course.started_on = {
:year => '2007',
:month => '3',
:day => '25'
}
result = @course['started_on']
result.should be_kind_of(Date)
result.year.should eql(2007)
result.month.should eql(3)
result.day.should eql(25)
end
end
describe 'and value is a string' do
it 'parses the string' do
@course.started_on = 'Dec 20th, 2006'
@course.started_on.month.should == 12
@course.started_on.day.should == 20
@course.started_on.year.should == 2006
end
end
it 'does not typecast non-date values' do
@course.started_on = 'not-date'
@course['started_on'].should eql('not-date')
end
end
describe 'when type primitive is a Time' do
describe 'and value given as a hash with keys like :year, :month, etc' do
it 'builds a Time instance from hash values' do
@course.ends_at = {
:year => '2006',
:month => '11',
:day => '23',
:hour => '12',
:min => '0',
:sec => '0'
}
result = @course['ends_at']
result.should be_kind_of(Time)
result.year.should eql(2006)
result.month.should eql(11)
result.day.should eql(23)
result.hour.should eql(12)
result.min.should eql(0)
result.sec.should eql(0)
end
end
describe 'and value is a string' do
it 'parses the string' do
t = Time.new(2011, 4, 1, 18, 50, 32, "+02:00")
@course.ends_at = t.strftime('%Y/%m/%d %H:%M:%S %z')
@course['ends_at'].year.should eql(t.year)
@course['ends_at'].month.should eql(t.month)
@course['ends_at'].day.should eql(t.day)
@course['ends_at'].hour.should eql(t.hour)
@course['ends_at'].min.should eql(t.min)
@course['ends_at'].sec.should eql(t.sec)
end
it 'parses the string without offset as UTC' do
t = Time.now.utc
@course.ends_at = t.strftime("%Y-%m-%d %H:%M:%S")
@course.ends_at.utc?.should be_true
@course['ends_at'].year.should eql(t.year)
@course['ends_at'].month.should eql(t.month)
@course['ends_at'].day.should eql(t.day)
@course['ends_at'].hour.should eql(t.hour)
@course['ends_at'].min.should eql(t.min)
@course['ends_at'].sec.should eql(t.sec)
end
end
it "converts a time value into utc" do
t = Time.new(2011, 4, 1, 18, 50, 32, "+02:00")
@course.ends_at = t
@course.ends_at.utc?.should be_true
@course.ends_at.to_i.should eql(Time.utc(2011, 4, 1, 16, 50, 32).to_i)
end
if RUBY_VERSION >= "1.9.1"
# In ruby 1.8.7 Time.parse will always return a value. D'OH
it 'does not typecast non-time values' do
@course.ends_at = 'not-time'
@course['ends_at'].should eql('not-time')
end
end
end
describe 'when type primitive is a Class' do
it 'returns same value if a class' do
value = Course
@course.klass = value
@course['klass'].should equal(value)
end
it 'returns the class if found' do
@course.klass = 'Course'
@course['klass'].should eql(Course)
end
it 'does not typecast non-class values' do
@course.klass = 'NoClass'
@course['klass'].should eql('NoClass')
end
end
describe 'when type primitive is a Boolean' do
[ true, 'true', 'TRUE', '1', 1, 't', 'T' ].each do |value|
it "returns true when value is #{value.inspect}" do
@course.active = value
@course['active'].should be_true
end
end
[ false, 'false', 'FALSE', '0', 0, 'f', 'F' ].each do |value|
it "returns false when value is #{value.inspect}" do
@course.active = value
@course['active'].should be_false
end
end
[ 'string', 2, 1.0, BigDecimal('1.0'), DateTime.now, Time.now, Date.today, Class, Object.new, ].each do |value|
it "does not typecast value #{value.inspect}" do
@course.active = value
@course['active'].should equal(value)
end
end
it "should respond to requests with ? modifier" do
@course.active = nil
@course.active?.should be_false
@course.active = false
@course.active?.should be_false
@course.active = true
@course.active?.should be_true
end
it "should respond to requests with ? modifier on TrueClass" do
@course.very_active = nil
@course.very_active?.should be_false
@course.very_active = false
@course.very_active?.should be_false
@course.very_active = true
@course.very_active?.should be_true
end
end
end

View file

@ -1,140 +0,0 @@
require "spec_helper"
describe CouchRest::Model::Validations do
describe "Uniqueness" do
context "basic" do
before(:all) do
@objs = ['title 1', 'title 2', 'title 3'].map{|t| WithUniqueValidation.create(:title => t)}
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
@obj = WithUniqueValidation.create(:title => 'title 4')
@obj.new?.should_not be_true
@obj.should be_valid
end
it "should not validate a non-unique document" do
@obj = WithUniqueValidation.create(:title => 'title 1')
@obj.should_not be_valid
@obj.errors[:title].should == ["has already been taken"]
end
it "should save already created document" do
@obj = @objs.first
@obj.save.should_not be_false
@obj.should be_valid
end
it "should allow own view to be specified" do
# validates_uniqueness_of :code, :view => 'all'
WithUniqueValidationView.create(:title => 'title 1', :code => '1234')
@obj = WithUniqueValidationView.new(:title => 'title 5', :code => '1234')
@obj.should_not be_valid
end
it "should raise an error if specified view does not exist" do
WithUniqueValidationView.validates_uniqueness_of :title, :view => 'fooobar'
@obj = WithUniqueValidationView.new(:title => 'title 2', :code => '12345')
lambda {
@obj.valid?
}.should raise_error
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
@obj = @objs[1]
@obj.class.should_not_receive('view_by')
@obj.class.should_receive('has_view?').and_return(true)
@obj.class.should_receive('view').and_return({'rows' => [ ]})
@obj.valid?
end
end
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
@obj = WithUniqueValidationProxy.new(:title => 'test 6')
proxy = @obj.should_receive('proxy').and_return(@obj.class)
@obj.valid?.should be_true
end
it "should allow specific view" do
@obj = WithUniqueValidationProxy.new(:title => 'test 7')
@obj.class.should_not_receive('view_by')
proxy = mock('Proxy')
@obj.should_receive('proxy').and_return(proxy)
proxy.should_receive('has_view?').and_return(true)
proxy.should_receive('view').and_return({'rows' => [ ]})
@obj.valid?
end
end
context "when proxied" do
it "should lookup the model_proxy" do
mp = mock(:ModelProxy)
mp.should_receive(:view).and_return({'rows' => []})
@obj = WithUniqueValidation.new(:title => 'test 8')
@obj.stub!(:model_proxy).twice.and_return(mp)
@obj.valid?
end
end
context "with a scope" do
before(:all) do
@objs = [['title 1', 1], ['title 2', 1], ['title 3', 1]].map{|t| WithScopedUniqueValidation.create(:title => t[0], :parent_id => t[1])}
@objs_nil = [['title 1', nil], ['title 2', nil], ['title 3', nil]].map{|t| WithScopedUniqueValidation.create(:title => t[0], :parent_id => t[1])}
end
it "should create the view" do
@objs.first.class.has_view?('by_parent_id_and_title')
end
it "should validate unique document" do
@obj = WithScopedUniqueValidation.create(:title => 'title 4', :parent_id => 1)
@obj.should be_valid
end
it "should validate unique document outside of scope" do
@obj = WithScopedUniqueValidation.create(:title => 'title 1', :parent_id => 2)
@obj.should be_valid
end
it "should validate non-unique document" do
@obj = WithScopedUniqueValidation.create(:title => 'title 1', :parent_id => 1)
@obj.should_not be_valid
@obj.errors[:title].should == ["has already been taken"]
end
it "should validate unique document will nil scope" do
@obj = WithScopedUniqueValidation.create(:title => 'title 4', :parent_id => nil)
@obj.should be_valid
end
it "should validate non-unique document with nil scope" do
@obj = WithScopedUniqueValidation.create(:title => 'title 1', :parent_id => nil)
@obj.should_not be_valid
@obj.errors[:title].should == ["has already been taken"]
end
end
end
end