Compare commits

..

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

102 changed files with 2556 additions and 6946 deletions

7
.gitignore vendored
View file

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

View file

@ -1,4 +0,0 @@
source :rubygems
gemspec

334
README.md
View file

@ -3,81 +3,35 @@
CouchRest Models adds additional functionality to the standard CouchRest Document class such as
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,
for validations and callbacks.
If your project is still running Rails 2.3, you'll have to continue using ExtendedDocument as
it is not possible to load ActiveModel into programs that do not use ActiveSupport 3.0.
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.
CouchRest Model only supports CouchDB 0.10.0 or newer.
## Install
### Gem
### From Gem
$ sudo gem install couchrest_model
CouchRest Model depends on Rails 3's ActiveModel which has not yet been released. You'll need to add
`--pre` to the end of the gem install until the dependencies are stable:
$ sudo gem install couchrest_model --pre
### Bundler
If you're using bundler, define a line similar to the following in your project's Gemfile:
If you're using bundler, just define a line similar to the following in your project's Gemfile:
gem 'couchrest_model'
### Configuration
You might also consider using the latest git repository. All tests should pass in the master code branch
but no guarantees!
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.
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:
development:
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.
The example config above for example would use a database called "project_test". Heres an example using the `use_database` call:
class Project < CouchRest::Model::Base
use_database 'sample'
end
# The database object would be provided as:
Project.database #=> "https://test:user@sample.cloudant.com:443/project_sample_test"
## Generators
### Configuration
$ rails generate couchrest_model:config
### Model
$ rails generate model person --orm=couchrest_model
gem 'couchrest_model', :git => 'git://github.com/couchrest/couchrest_model.git'
## General Usage
require 'couchrest_model'
@ -109,22 +63,269 @@ The example config above for example would use a database called "project_test".
@cat.new? # false
@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:
Only attributes with a property definition will be stored be CouchRest Model (as opposed
to a normal CouchRest Document which will store everything). To help prevent confusion,
a property should be considered as the definition of an attribute. An attribute must be associated
with a property, but a property may not have any attributes associated if none have been set.
bundle install
That should set everything up for `rake spec` to be run correctly. Update the couchrest_model.gemspec if your alterations
use different gems.
In its simplest form, a property
will only create a getter and setter passing all attribute data directly to the database. Assuming the attribute
provided responds to `to_json`, there will not be any problems saving it, but when loading the
data back it will either be a string, number, array, or hash:
### 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!
Booleans or TrueClass will also 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.
Defining a property as read-only will mean that its value is set only when read from the
database and that it will not have a setter method. 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!
## Property Arrays
An attribute may also 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', :purchases => 1.month.ago}])
@cat.toys.first.class == CatToy
@cat.toys.first.name == 'mouse'
Additionally, any hashes sent to the property will automatically be converted:
@cat.toys << {:name => 'catnip ball'}
@cat.toys.last.is_a?(CatToy) # True!
Of course, 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, the latest version of CouchRest Model (> 1.0.0) supports creating
anonymous classes:
class Cat << CouchRest::Model::Base
property :name, String
property :toys do |toy|
toy.property :name, String
toy.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'
Using this method of anonymous classes will *only* create arrays of objects.
## Assocations
Two types at the moment:
belongs_to :person
collection_of :tags
TODO: Document properly!
## 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!
## Notable Issues
CouchRest Model uses active_support for some of its internals. Ensure you have a stable active support gem installed
or at least 3.0.0.beta4.
JSON gem versions 1.4.X are kown to cause problems with stack overflows and general badness. Version 1.2.4 appears to work fine.
## Ruby on Rails
CouchRest Model is compatible with rails and provides some ActiveRecord-like methods.
The CouchRest companion rails project
[http://github.com/hpoydar/couchrest-rails](http://github.com/hpoydar/couchrest-rails) is great
for provided default connection details for your database. At the time of writting however it
does not provide explicit support for CouchRest Model.
CouchRest Model and the original CouchRest ExtendedDocument do not share the same namespace,
as such you should not have any problems using them both at the same time. This might
help with migrations.
### Rails 3.0
In your Gemfile require the gem with a simple line:
gem "couchrest_model"
## 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
@ -134,4 +335,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)

View file

@ -1,20 +1,54 @@
require 'rubygems'
require 'bundler'
require 'rspec/core/rake_task'
require 'rake'
require "rake/rdoctask"
Bundler::GemHelper.install_tasks
$LOAD_PATH.unshift File.expand_path("../lib", __FILE__)
require 'couchrest_model'
begin
require 'spec/rake/spectask'
rescue LoadError
puts <<-EOS
To use rspec for testing you must install rspec gem:
gem install rspec
EOS
exit(0)
end
begin
require 'jeweler'
Jeweler::Tasks.new do |gemspec|
gemspec.name = "couchrest_model"
gemspec.summary = "Extends the CouchRest Document for advanced modelling."
gemspec.description = "CouchRest Model provides aditional features to the standard CouchRest Document class such as properties, view designs, associations, callbacks, typecasting and validations."
gemspec.email = "jchris@apache.org"
gemspec.homepage = "http://github.com/couchrest/couchrest_model"
gemspec.authors = ["J. Chris Anderson", "Matt Aimonetti", "Marcos Tapajos", "Will Leinweber", "Sam Lown"]
gemspec.extra_rdoc_files = %w( README.md LICENSE THANKS.md )
gemspec.files = %w( LICENSE README.md Rakefile THANKS.md history.txt couchrest.gemspec) + Dir["{examples,lib,spec}/**/*"] - Dir["spec/tmp"]
gemspec.has_rdoc = true
gemspec.add_dependency("couchrest", ">= 1.0.0")
gemspec.add_dependency("mime-types", ">= 1.15")
gemspec.add_dependency("activesupport", ">= 2.3.5")
gemspec.add_dependency("activemodel", ">= 3.0.0.beta4")
gemspec.add_dependency("tzinfo", ">= 0.3.22")
gemspec.version = CouchRest::Model::VERSION
gemspec.date = Time.now.strftime("%Y-%m-%d")
gemspec.require_path = "lib"
end
rescue LoadError
puts "Jeweler not available. Install it with: gem install jeweler"
end
desc "Run all specs"
RSpec::Core::RakeTask.new(:spec) do |spec|
spec.rspec_opts = ["--color"]
spec.pattern = 'spec/**/*_spec.rb'
Spec::Rake::SpecTask.new('spec') do |t|
t.spec_opts = ["--color"]
t.spec_files = FileList['spec/**/*_spec.rb']
end
desc "Print specdocs"
RSpec::Core::RakeTask.new(:doc) do |spec|
spec.rspec_opts = ["--format", "specdoc"]
spec.pattern = 'spec/*_spec.rb'
Spec::Rake::SpecTask.new(:doc) do |t|
t.spec_opts = ["--format", "specdoc"]
t.spec_files = FileList['spec/*_spec.rb']
end
desc "Generate the rdoc"
@ -35,4 +69,4 @@ module Rake
end
Rake.remove_task("github:release")
Rake.remove_task("release")
Rake.remove_task("release")

View file

@ -1 +0,0 @@
1.1.2

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

@ -1,36 +1,155 @@
# Generated by jeweler
# DO NOT EDIT THIS FILE DIRECTLY
# Instead, edit Jeweler::Tasks in Rakefile, and run the gemspec command
# -*- encoding: utf-8 -*-
Gem::Specification.new do |s|
s.name = %q{couchrest_model}
s.version = `cat VERSION`.strip
s.version = "1.0.0.beta7"
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.date = File.mtime('VERSION')
s.date = %q{2010-08-11}
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.extra_rdoc_files = [
"LICENSE",
"README.md",
"THANKS.md"
"README.md",
"THANKS.md"
]
s.files = [
"LICENSE",
"README.md",
"Rakefile",
"THANKS.md",
"examples/model/example.rb",
"history.txt",
"lib/couchrest/model.rb",
"lib/couchrest/model/associations.rb",
"lib/couchrest/model/attribute_protection.rb",
"lib/couchrest/model/attributes.rb",
"lib/couchrest/model/base.rb",
"lib/couchrest/model/callbacks.rb",
"lib/couchrest/model/casted_array.rb",
"lib/couchrest/model/casted_model.rb",
"lib/couchrest/model/class_proxy.rb",
"lib/couchrest/model/collection.rb",
"lib/couchrest/model/design_doc.rb",
"lib/couchrest/model/document_queries.rb",
"lib/couchrest/model/errors.rb",
"lib/couchrest/model/extended_attachments.rb",
"lib/couchrest/model/persistence.rb",
"lib/couchrest/model/properties.rb",
"lib/couchrest/model/property.rb",
"lib/couchrest/model/support/couchrest.rb",
"lib/couchrest/model/support/hash.rb",
"lib/couchrest/model/typecast.rb",
"lib/couchrest/model/validations.rb",
"lib/couchrest/model/validations/casted_model.rb",
"lib/couchrest/model/validations/locale/en.yml",
"lib/couchrest/model/validations/uniqueness.rb",
"lib/couchrest/model/views.rb",
"lib/couchrest_model.rb",
"spec/couchrest/assocations_spec.rb",
"spec/couchrest/attachment_spec.rb",
"spec/couchrest/attribute_protection_spec.rb",
"spec/couchrest/base_spec.rb",
"spec/couchrest/casted_model_spec.rb",
"spec/couchrest/casted_spec.rb",
"spec/couchrest/class_proxy_spec.rb",
"spec/couchrest/inherited_spec.rb",
"spec/couchrest/persistence_spec.rb",
"spec/couchrest/property_spec.rb",
"spec/couchrest/subclass_spec.rb",
"spec/couchrest/validations.rb",
"spec/couchrest/view_spec.rb",
"spec/fixtures/attachments/README",
"spec/fixtures/attachments/couchdb.png",
"spec/fixtures/attachments/test.html",
"spec/fixtures/base.rb",
"spec/fixtures/more/article.rb",
"spec/fixtures/more/card.rb",
"spec/fixtures/more/cat.rb",
"spec/fixtures/more/client.rb",
"spec/fixtures/more/course.rb",
"spec/fixtures/more/event.rb",
"spec/fixtures/more/invoice.rb",
"spec/fixtures/more/person.rb",
"spec/fixtures/more/question.rb",
"spec/fixtures/more/sale_entry.rb",
"spec/fixtures/more/sale_invoice.rb",
"spec/fixtures/more/service.rb",
"spec/fixtures/more/user.rb",
"spec/fixtures/views/lib.js",
"spec/fixtures/views/test_view/lib.js",
"spec/fixtures/views/test_view/only-map.js",
"spec/fixtures/views/test_view/test-map.js",
"spec/fixtures/views/test_view/test-reduce.js",
"spec/spec.opts",
"spec/spec_helper.rb",
"utils/remap.rb",
"utils/subset.rb"
]
s.homepage = %q{http://github.com/couchrest/couchrest_model}
s.rubygems_version = %q{1.3.7}
s.summary = %q{Extends the CouchRest Document for advanced modelling.}
s.files = `git ls-files`.split("\n")
s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n")
s.executables = `git ls-files -- bin/*`.split("\n").map{ |f| File.basename(f) }
s.rdoc_options = ["--charset=UTF-8"]
s.require_paths = ["lib"]
s.rubygems_version = %q{1.3.6}
s.summary = %q{Extends the CouchRest Document for advanced modelling.}
s.test_files = [
"spec/spec_helper.rb",
"spec/couchrest/property_spec.rb",
"spec/couchrest/casted_spec.rb",
"spec/couchrest/subclass_spec.rb",
"spec/couchrest/persistence_spec.rb",
"spec/couchrest/casted_model_spec.rb",
"spec/couchrest/attribute_protection_spec.rb",
"spec/couchrest/assocations_spec.rb",
"spec/couchrest/validations.rb",
"spec/couchrest/view_spec.rb",
"spec/couchrest/inherited_spec.rb",
"spec/couchrest/attachment_spec.rb",
"spec/couchrest/class_proxy_spec.rb",
"spec/couchrest/base_spec.rb",
"spec/fixtures/base.rb",
"spec/fixtures/more/card.rb",
"spec/fixtures/more/event.rb",
"spec/fixtures/more/user.rb",
"spec/fixtures/more/sale_invoice.rb",
"spec/fixtures/more/article.rb",
"spec/fixtures/more/service.rb",
"spec/fixtures/more/invoice.rb",
"spec/fixtures/more/person.rb",
"spec/fixtures/more/question.rb",
"spec/fixtures/more/cat.rb",
"spec/fixtures/more/client.rb",
"spec/fixtures/more/sale_entry.rb",
"spec/fixtures/more/course.rb",
"examples/model/example.rb"
]
s.add_dependency(%q<couchrest>, "~> 1.1.2")
s.add_dependency(%q<mime-types>, "~> 1.15")
s.add_dependency(%q<activemodel>, "~> 3.0")
s.add_dependency(%q<tzinfo>, "~> 0.3.22")
s.add_development_dependency(%q<rspec>, "~> 2.6.0")
s.add_development_dependency(%q<json>, ["~> 1.5.1"])
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")
if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 3
if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<couchrest>, [">= 1.0.0"])
s.add_runtime_dependency(%q<mime-types>, [">= 1.15"])
s.add_runtime_dependency(%q<activesupport>, [">= 2.3.5"])
s.add_runtime_dependency(%q<activemodel>, [">= 3.0.0.beta4"])
s.add_runtime_dependency(%q<tzinfo>, [">= 0.3.22"])
else
s.add_dependency(%q<couchrest>, [">= 1.0.0"])
s.add_dependency(%q<mime-types>, [">= 1.15"])
s.add_dependency(%q<activesupport>, [">= 2.3.5"])
s.add_dependency(%q<activemodel>, [">= 3.0.0.beta4"])
s.add_dependency(%q<tzinfo>, [">= 0.3.22"])
end
else
s.add_dependency(%q<couchrest>, [">= 1.0.0"])
s.add_dependency(%q<mime-types>, [">= 1.15"])
s.add_dependency(%q<activesupport>, [">= 2.3.5"])
s.add_dependency(%q<activemodel>, [">= 3.0.0.beta4"])
s.add_dependency(%q<tzinfo>, [">= 0.3.22"])
end
end

View file

@ -1,140 +1,14 @@
# CouchRest Model Change History
## 1.1.3
* CouchRest::Model::Base.respond_to_missing? and respond_to? (Kim Burgestrand)
## 1.1.2 - 2011-07-23
* Minor fixes
* Upgrade to couchrest 1.1.2
* Override as_couch_json to ensure nil values not stored
* Removing restriction that prohibited objects that cast as an array to be loaded.
## 1.1.1 - 2011-07-04
* Minor fix
* Bumping CouchRest version dependency for important initialize method fix.
* Ensuring super on Embeddable#initialize can be called.
## 1.1.0 - 2011-06-25
* Major Alterations
* CastedModel no longer requires a Hash. Automatically includes all required methods.
* CastedModel module renamed to Embeddable (old still works!)
* Minor Fixes
* Validation callbacks now support context (thanks kostia)
* Document comparisons now performed using database and document ID (pointer by neocsr)
* Automatic config generation now supported (thanks lucasrenan)
* Comparing documents resorts to Hash comparison if both IDs are nil. (pointer by kostia)
## 1.1.0.rc1 - 2011-06-08
* New Features
* Properties with a nil value are now no longer sent to the database.
* Now possible to build new objects via CastedArray#build
* Implement #get! and #find! class methods
* Now is possible delete particular elements in casted array(Kostiantyn Kahanskyi)
* Minor fixes
* #as_json now correctly uses ActiveSupports methods.
* Rails 3.1 support (Peter Williams)
* Initialization blocks when creating new models (Peter Williams)
* Removed railties dependency (DAddYE)
* DesignDoc cache refreshed if a database is deleted.
* Fixing dirty tracking on collection_of association.
* Uniqueness Validation views created on initialization, not on demand!
* #destroy freezes object instead of removing _id and _rev, better for callbacks (pointer by karmi)
* #destroyed? method now available
* #reload no longer uses Hash#merge! which was causing issues with dirty tracking on casted models. (pointer by kostia)
* Non-property mass assignment on #new no longer possible without :directly_set_attributes option.
* Using CouchRest 1.1.0.pre3. (No more Hashes!)
* Fixing problem assigning a CastedHash to a property declared as a Hash (Kostiantyn Kahanskyi, gfmtim)
## 1.1.0.beta5 - 2011-04-30
* Major changes:
* Database auto configuration, with connection options!
* Changed default CouchRest Model type to 'type' to be more consistent with ActiveRecord's reserverd words we're all used to (sorry for the change again!!)
* Minor changes
* Added filter option to designs (Used with CouchDB _changes feeds)
## 1.1.0.beta4
* Major changes:
* 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:
* Added "View" object for dynamic view queries
* Added easy to use proxy_for and proxied_by class methods for proxying data
* Minor enhancements:
* A yield parameter in an anonymous casted model property block is no longer required (@samlown)
* 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)
* 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)
## CouchRest Model 1.0.0
== Next Version
* Major enhancements
* Support for configuration module and "model_type_key" option for overriding model's type key
* Added "mass_assign_any_attribute" configuration option to allow setting anything via the attribute= method.
* Minor enhancements
* Fixing find("") issue (thanks epochwolf)
* Altered protected attributes so that hash provided to #attributes= is not modified
* Altering typecasting for floats to better handle commas and points
* Fixing the lame pagination bug where database url (and pass!!) were included in view requests (Thanks James Hayton)
Notes:
* 2010-10-22 @samlown:
* ActiveModel Attribute support was added but has now been removed due to major performance issues.
Until these have been resolved (if possible?!) they should not be included. See the
'active_model_attrs' if you'd like to test.
## CouchRest Model 1.0.0.beta8
* Major enhancements
* Added model generator
* Minor enhancements
* Raise error on adding objects to "collection_of" without an id
* Allow mixing of protected and accessible properties. Any unspecified properties are now assumed to be protected by default
* Parsing times without zone
* Using latest rspec (2.0.0.beta.19)
## CouchRest Model 1.0.0.beta7
== CouchRest Model 1.0.0.beta7
* Major enhancements
* Renamed ExtendedDocument to CouchRest::Model
* Added initial support for simple belongs_to associations
* Added initial support for simple belongs_to associations
* Added support for basic collection_of association (unique to document databases!)
* Moved Validation to ActiveModel
* Moved Callbacks to ActiveModel
@ -146,7 +20,7 @@ Notes:
* Removed support for auto_validate! and :length on properties
## 1.0.0.beta6
== 1.0.0.beta6
* Major enhancements
* Added support for anonymous CastedModels defined in Documents
@ -160,12 +34,12 @@ Notes:
* 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.
## 1.0.0.beta5
== 1.0.0.beta5
* Minor enhancements
* Added 'find' alias for 'get' for easier rails transition
## 1.0.0.beta3
== 1.0.0.beta3
* Minor enhancements
* Removed Validation by default, requires too many structure changes (FAIL)
@ -175,12 +49,12 @@ Notes:
* Added support for setting type directly on property (Sam Lown)
## 1.0.0.beta2
== 1.0.0.beta2
* Minor enhancements
* Enable Validation by default and refactored location (Sam Lown)
## 1.0.0.beta
== 1.0.0.beta
* Major enhancements
* Separated ExtendedDocument from main CouchRest gem (Sam Lown)
@ -188,22 +62,22 @@ Notes:
* Minor enhancements
* active_support included by default
## 0.37
== 0.37
* Minor enhancements
* Added gemspec (needed for Bundler install) (Tapajós)
## 0.36
== 0.36
* Major enhancements
* Adds support for continuous replication (sauy7)
* Automatic Type Casting (Alexander Uvarov, Sam Lown, Tim Heighes, Will Leinweber)
* Added a search method to CouchRest:Database to search the documents in a given database. (Dave Farkas, Arnaud Berthomier, John Wood)
* Minor enhancements
* Provide a description of the timeout error (John Wood)
## 0.35
== 0.35
* Major enhancements
* CouchRest::ExtendedDocument allow chaining the inherit class callback (Kenneth Kalmer) - http://github.com/couchrest/couchrest/issues#issue/8
@ -219,7 +93,7 @@ Notes:
* 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)
## 0.34
== 0.34
* Major enhancements
@ -228,9 +102,9 @@ Notes:
* Adds attribute protection to properties. (Will Leinweber)
* Improved CouchRest::Database#save_doc, added "batch" mode to significantly speed up saves at cost of lower durability gurantees. (Igal Koshevoy)
* Added CouchRest::Database#bulk_save_doc and #batch_save_doc as human-friendlier wrappers around #save_doc. (Igal Koshevoy)
* Minor enhancements
* Minor enhancements
* Fix content_type handling for attachments
* Fixed a bug in the pagination code that caused it to paginate over records outside of the scope of the view parameters.(John Wood)
* Removed amount_pages calculation for the pagination collection, since it cannot be reliably calculated without a view.(John Wood)
@ -244,14 +118,14 @@ Notes:
* Fix Initialization of ExtendentDocument model shouldn't failed on a nil value in argument (deepj)
* Change to use Jeweler and Gemcutter (Marcos Tapajós)
## 0.33
== 0.33
* Major enhancements
* Added a new Rack logger middleware letting you log/save requests/queries (Matt Aimonetti)
* Minor enhancements
* Minor enhancements
* Added #amount_pages to a paginated result array (Matt Aimonetti)
* Ruby 1.9.2 compatible (Matt Aimonetti)
* Added a property? method for property cast as :boolean (John Wood)
@ -259,50 +133,50 @@ Notes:
* Created a new abstraction layer for the REST API (Matt Aimonetti)
* Bug fix: made ExtendedDocument#all compatible with Couch 0.10 (tc)
## 0.32
== 0.32
* Major enhancements
* ExtendedDocument.get doesn't raise an exception anymore. If no documents are found nil is returned.
* ExtendedDocument.get! works the say #get used to work and will raise an exception if a document isn't found.
* Minor enhancements
* Minor enhancements
* Bug fix: Model.all(:keys => [1,2]) was not working (Matt Aimonetti)
* Added ValidationErrors#count in order to play nicely with Rails (Peter Wagenet)
* Bug fix: class proxy design doc refresh (Daniel Kirsh)
* Bug fix: the count method on the proxy collection was missing (Daniel Kirsch)
* Added #amount_pages to a paginated collection. (Matt Aimonetti)
## 0.31
== 0.31
* Major enhancements
* Created an abstraction HTTP layer to support different http adapters (Matt Aimonetti)
* Added ExtendedDocument.create({}) and #create!({}) so you don't have to do Model.new.create (Matt Aimonetti)
* Minor enhancements
* Added an init.rb file for easy usage as a Rails plugin (Aaron Quint)
* Bug fix: pagination shouldn't die on empty results (Arnaud Berthomier)
* Optimized ExtendedDocument.count to run about 3x faster (Matt Aimonetti)
* Added Float casting (Ryan Felton & Matt Aimonetti)
## 0.30
== 0.30
* Major enhancements
* Added support for pagination (John Wood)
* Improved performance when initializing documents with timestamps (Matt Aimonetti)
* Minor enhancements
* Extended the API to retrieve an attachment URI (Matt Aimonetti)
* Bug fix: default value should be able to be set as false (Alexander Uvarov)
* Bug fix: validates_is_numeric should be able to properly validate a Float instance (Rob Kaufman)
* Bug fix: fixed the Timeout implementation (Seth Falcon)
---
Unfortunately, before 0.30 we did not keep a track of the modifications made to CouchRest.

View file

@ -1 +1 @@
require File.join(File.dirname(__FILE__),'lib', 'couchrest', 'model')
require File.join(File.dirname(__FILE__),'lib', 'couchrest', 'extended_document')

View file

@ -3,7 +3,7 @@ module CouchRest
module Model
VERSION = File.read(File.expand_path('../../../VERSION', __FILE__)).strip
VERSION = "1.0.0.beta7"
end

View file

@ -11,37 +11,30 @@ module CouchRest
module ClassMethods
# 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)
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
raise "Unable to convert class name into Constant for #{self.name}##{attrib}"
end
create_belongs_to_getter(attrib, opts)
create_belongs_to_setter(attrib, opts)
prop = property(opts[:foreign_key], opts)
create_belongs_to_getter(attrib, prop, opts)
create_belongs_to_setter(attrib, prop, opts)
prop
end
# Provide access to a collection of objects where the associated
@ -84,50 +77,44 @@ module CouchRest
# frequently! Use with prudence.
#
def collection_of(attrib, *options)
opts = merge_belongs_to_association_options(attrib, options.first)
opts[:foreign_key] = opts[:foreign_key].pluralize
opts = {
: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
property(opts[:foreign_key], [], opts)
prop = property(opts[:foreign_key], [], opts)
create_collection_of_property_setter(attrib, opts)
create_collection_of_getter(attrib, opts)
create_collection_of_setter(attrib, opts)
create_collection_of_property_setter(attrib, prop, opts)
create_collection_of_getter(attrib, prop, opts)
create_collection_of_setter(attrib, prop, opts)
prop
end
private
def merge_belongs_to_association_options(attrib, options = nil)
opts = {
: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)
def create_belongs_to_getter(attrib, property, options)
base = options[:proxy] || options[:class_name]
class_eval <<-EOS, __FILE__, __LINE__ + 1
def #{attrib}
@#{attrib} ||= #{options[:foreign_key]}.nil? ? nil : #{options[:proxy]}.get(self.#{options[:foreign_key]})
@#{attrib} ||= #{options[:foreign_key]}.nil? ? nil : #{base}.get(self.#{options[:foreign_key]})
end
EOS
end
def create_belongs_to_setter(attrib, options)
def create_belongs_to_setter(attrib, property, options)
class_eval <<-EOS, __FILE__, __LINE__ + 1
def #{attrib}=(value)
self.#{options[:foreign_key]} = value.nil? ? nil : value.id
@ -138,7 +125,7 @@ module CouchRest
### 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
class_eval <<-EOS, __FILE__, __LINE__ + 1
def #{options[:foreign_key]}=(value)
@ -148,20 +135,21 @@ module CouchRest
EOS
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
def #{attrib}(reload = false)
return @#{attrib} unless @#{attrib}.nil? or reload
ary = self.#{options[:foreign_key]}.collect{|i| #{options[:proxy]}.get(i)}
@#{attrib} = ::CouchRest::Model::CollectionOfProxy.new(ary, find_property('#{options[:foreign_key]}'), self)
ary = self.#{options[:foreign_key]}.collect{|i| #{base}.get(i)}
@#{attrib} = ::CouchRest::CollectionOfProxy.new(ary, self, '#{options[:foreign_key]}')
end
EOS
end
def create_collection_of_setter(attrib, options)
def create_collection_of_setter(attrib, property, options)
class_eval <<-EOS, __FILE__, __LINE__ + 1
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
EOS
end
@ -169,63 +157,67 @@ module CouchRest
end
end
end
# Special proxy for a collection of items so that adding and removing
# to the list automatically updates the associated property.
class CollectionOfProxy < CastedArray
# Special proxy for a collection of items so that adding and removing
# to the list automatically updates the associated property.
class CollectionOfProxy < Array
attr_accessor :property
attr_accessor :casted_by
def initialize(array, property, parent)
(array ||= []).compact!
super(array, property, parent)
casted_by[casted_by_property.to_s] = [] # replace the original array!
array.compact.each do |obj|
check_obj(obj)
casted_by[casted_by_property.to_s] << obj.id
end
end
def << obj
def initialize(array, casted_by, property)
self.property = property
self.casted_by = casted_by
(array ||= []).compact!
casted_by[property.to_s] = [] # replace the original array!
array.compact.each do |obj|
check_obj(obj)
casted_by[casted_by_property.to_s] << obj.id
super(obj)
casted_by[property.to_s] << obj.id
end
super(array)
end
def << obj
check_obj(obj)
casted_by[property.to_s] << obj.id
super(obj)
end
def push(obj)
check_obj(obj)
casted_by[property.to_s].push obj.id
super(obj)
end
def unshift(obj)
check_obj(obj)
casted_by[property.to_s].unshift obj.id
super(obj)
end
def push(obj)
check_obj(obj)
casted_by[casted_by_property.to_s].push obj.id
super(obj)
end
def []= index, obj
check_obj(obj)
casted_by[property.to_s][index] = obj.id
super(index, obj)
end
def unshift(obj)
check_obj(obj)
casted_by[casted_by_property.to_s].unshift obj.id
super(obj)
end
def pop
casted_by[property.to_s].pop
super
end
def shift
casted_by[property.to_s].shift
super
end
def []= index, obj
check_obj(obj)
casted_by[casted_by_property.to_s][index] = obj.id
super(index, obj)
end
def pop
casted_by[casted_by_property.to_s].pop
super
end
def shift
casted_by[casted_by_property.to_s].shift
super
end
protected
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?
end
protected
def check_obj(obj)
raise "Object cannot be added to #{casted_by.class.to_s}##{property.to_s} collection unless saved" if obj.new?
end
end
end

View file

@ -0,0 +1,74 @@
module CouchRest
module Model
module AttributeProtection
# Attribute protection from mass assignment to CouchRest properties
#
# Protected methods will be removed from
# * new
# * update_attributes
# * upate_attributes_without_saving
# * attributes=
#
# There are two modes of protection
# 1) Declare accessible poperties, assume all the rest are protected
# property :name, :accessible => true
# property :admin # this will be automatically protected
#
# 2) Declare protected properties, assume all the rest are accessible
# property :name # this will not be protected
# property :admin, :protected => true
#
# Note: you cannot set both flags in a single class
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def accessible_properties
properties.select { |prop| prop.options[:accessible] }
end
def protected_properties
properties.select { |prop| prop.options[:protected] }
end
end
def accessible_properties
self.class.accessible_properties
end
def protected_properties
self.class.protected_properties
end
def remove_protected_attributes(attributes)
protected_names = properties_to_remove_from_mass_assignment.map { |prop| prop.name }
return attributes if protected_names.empty?
attributes.reject! do |property_name, property_value|
protected_names.include?(property_name.to_s)
end
attributes || {}
end
private
def properties_to_remove_from_mass_assignment
has_protected = !protected_properties.empty?
has_accessible = !accessible_properties.empty?
if !has_protected && !has_accessible
[]
elsif has_protected && !has_accessible
protected_properties
elsif has_accessible && !has_protected
properties.reject { |prop| prop.options[:accessible] }
else
raise "Set either :accessible or :protected for #{self.class}, but not both"
end
end
end
end
end

View file

@ -0,0 +1,75 @@
module CouchRest
module Model
module Attributes
## Support for handling attributes
#
# This would be better in the properties file, but due to scoping issues
# this is not yet possible.
#
def prepare_all_attributes(doc = {}, options = {})
apply_all_property_defaults
if options[:directly_set_attributes]
directly_set_read_only_attributes(doc)
else
remove_protected_attributes(doc)
end
directly_set_attributes(doc) unless doc.nil?
end
# Takes a hash as argument, and applies the values by using writer methods
# for each key. It doesn't save the document at the end. Raises a NoMethodError if the corresponding methods are
# missing. In case of error, no attributes are changed.
def update_attributes_without_saving(hash)
# Remove any protected and update all the rest. Any attributes
# which do not have a property will simply be ignored.
attrs = remove_protected_attributes(hash)
directly_set_attributes(attrs)
end
alias :attributes= :update_attributes_without_saving
# Takes a hash as argument, and applies the values by using writer methods
# for each key. Raises a NoMethodError if the corresponding methods are
# missing. In case of error, no attributes are changed.
def update_attributes(hash)
update_attributes_without_saving hash
save
end
private
def directly_set_attributes(hash)
hash.each do |attribute_name, attribute_value|
if self.respond_to?("#{attribute_name}=")
self.send("#{attribute_name}=", hash.delete(attribute_name))
end
end
end
def directly_set_read_only_attributes(hash)
property_list = self.properties.map{|p| p.name}
hash.each do |attribute_name, attribute_value|
next if self.respond_to?("#{attribute_name}=")
if property_list.include?(attribute_name)
write_attribute(attribute_name, hash.delete(attribute_name))
end
end
end
def set_attributes(hash)
attrs = remove_protected_attributes(hash)
directly_set_attributes(attrs)
end
def check_properties_exist(attrs)
property_list = self.properties.map{|p| p.name}
attrs.each do |attribute_name, attribute_value|
raise NoMethodError, "Property #{attribute_name} not created" unless respond_to?("#{attribute_name}=") or property_list.include?(attribute_name)
end
end
end
end
end

View file

@ -1,36 +1,29 @@
module CouchRest
module Model
class Base < CouchRest::Document
class Base < Document
extend ActiveModel::Naming
include CouchRest::Model::Configuration
include CouchRest::Model::Connection
include CouchRest::Model::Persistence
include CouchRest::Model::DocumentQueries
include CouchRest::Model::Callbacks
include CouchRest::Model::DocumentQueries
include CouchRest::Model::Views
include CouchRest::Model::DesignDoc
include CouchRest::Model::ExtendedAttachments
include CouchRest::Model::ClassProxy
include CouchRest::Model::Proxyable
include CouchRest::Model::Collection
include CouchRest::Model::PropertyProtection
include CouchRest::Model::AttributeProtection
include CouchRest::Model::Attributes
include CouchRest::Model::Associations
include CouchRest::Model::Validations
include CouchRest::Model::Callbacks
include CouchRest::Model::Designs
include CouchRest::Model::CastedBy
include CouchRest::Model::Dirty
include CouchRest::Model::Callbacks
def self.subclasses
@subclasses ||= []
end
def self.inherited(subklass)
super
subklass.send(:include, CouchRest::Model::Properties)
subklass.class_eval <<-EOS, __FILE__, __LINE__ + 1
def self.inherited(subklass)
super
@ -41,33 +34,28 @@ module CouchRest
EOS
subclasses << subklass
end
# Accessors
attr_accessor :casted_by
# Instantiate a new CouchRest::Model::Base by preparing all properties
# using the provided document hash.
#
# 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
#
# If a block is provided the new model will be passed into the
# block so that it can be populated.
def initialize(attributes = {}, options = {})
super()
prepare_all_attributes(attributes, options)
# set the instance's database, if provided
self.database = options[:database] unless options[:database].nil?
def initialize(doc = {}, options = {})
prepare_all_attributes(doc, options)
super(doc)
unless self['_id'] && self['_rev']
self[self.model_type_key] = self.class.to_s
self['couchrest-type'] = self.class.to_s
end
yield self if block_given?
after_initialize if respond_to?(:after_initialize)
run_callbacks(:initialize) { self }
end
# Temp solution to make the view_by methods available
def self.method_missing(m, *args, &block)
if has_view?(m)
@ -81,49 +69,43 @@ module CouchRest
end
super
end
# compatbility for 1.8, it does not use respond_to_missing?
# thing is, when using it like this only, doing method(:find_by_view)
# will throw an error
def self.respond_to?(m, include_private = false)
super || respond_to_missing?(m, include_private)
### instance methods
# 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.base_doc
end
# ruby 1.9 feature
# this allows ruby to know that the method is defined using
# method_missing, and as such, method(:find_by_view) will actually
# give a Method back, and not throw an error like in 1.8!
def self.respond_to_missing?(m, include_private = false)
has_view?(m) || has_view?(m.to_s[/^find_(by_.+)/, 1])
# Checks if we're the top document
def base_doc?
!@casted_by
end
## 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
def to_key
new? ? nil : [id]
new? ? nil : [id]
end
alias :to_param :id
alias :new_record? :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

View file

@ -5,23 +5,22 @@ module CouchRest #:nodoc:
module Callbacks
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
extend ActiveModel::Callbacks
include ActiveModel::Validations::Callbacks
define_model_callbacks :initialize, :only => :after
define_model_callbacks :create, :destroy, :save, :update
define_model_callbacks \
:create,
:destroy,
:save,
:update,
:validate
end
def valid?(*) #nodoc
_run_validation_callbacks { super }
end
end
end

View file

@ -5,77 +5,33 @@
module CouchRest::Model
class CastedArray < Array
include CouchRest::Model::CastedBy
include CouchRest::Model::Dirty
attr_accessor :casted_by_property
attr_accessor :casted_by
attr_accessor :property
def initialize(array, property, parent = nil)
self.casted_by_property = property
self.casted_by = parent unless parent.nil?
def initialize(array, property)
self.property = property
super(array)
end
# Adding new entries
def << obj
super(instantiate_and_cast(obj))
end
def push(obj)
super(instantiate_and_cast(obj))
end
def unshift(obj)
super(instantiate_and_cast(obj))
end
def []= index, obj
value = instantiate_and_cast(obj, false)
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
super(index, instantiate_and_cast(obj))
end
protected
def instantiate_and_cast(obj, change = true)
property = casted_by_property
couchrest_parent_will_change! if change && use_dirty?
if casted_by && property && obj.class != property.type_class
property.cast_value(casted_by, obj)
def instantiate_and_cast(obj)
if self.casted_by && self.property && obj.class != self.property.type_class
self.property.cast_value(self.casted_by, obj)
else
obj.casted_by = casted_by if obj.respond_to?(:casted_by)
obj.casted_by_property = casted_by_property if obj.respond_to?(:casted_by_property)
obj.casted_by = self.casted_by if obj.respond_to?(:casted_by)
obj
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 Embeddable
module CastedModel
extend ActiveSupport::Concern
# Include Attributes early to ensure super() will work
include CouchRest::Attributes
included do
include CouchRest::Model::Configuration
include CouchRest::Model::AttributeProtection
include CouchRest::Model::Attributes
include CouchRest::Model::Callbacks
include CouchRest::Model::Properties
include CouchRest::Model::PropertyProtection
include CouchRest::Model::Associations
include CouchRest::Model::Validations
include CouchRest::Model::Callbacks
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
attr_accessor :casted_by
end
# Initialize a new Casted Model. Accepts the same
# options as CouchRest::Model::Base for preparing and initializing
# attributes.
def initialize(keys = {}, options = {})
def initialize(keys = {})
raise StandardError unless self.is_a? Hash
prepare_all_attributes(keys)
super()
prepare_all_attributes(keys, options)
run_callbacks(:initialize) { self }
end
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
# False if the casted model has already
# been saved in the containing document
def new?
casted_by.nil? ? true : casted_by.new?
@casted_by.nil? ? true : @casted_by.new?
end
alias :new_record? :new?
@ -53,7 +53,7 @@ module CouchRest::Model
end
alias :to_key :id
alias :to_param :id
# Sets the attributes from a hash
def update_attributes_without_saving(hash)
hash.each do |k, v|
@ -64,15 +64,5 @@ module CouchRest::Model
end
end
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

View file

@ -75,26 +75,13 @@ module CouchRest
doc
end
def last(opts = {})
doc = @klass.last({:database => @database}.merge(opts))
doc.database = @database if doc && doc.respond_to?(:database)
doc
end
def get(id)
doc = @klass.get(id, @database)
doc.database = @database if doc && doc.respond_to?(:database)
doc
end
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
def has_view?(view)

View file

@ -1,13 +1,7 @@
module CouchRest
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
def self.included(base)
base.extend(ClassMethods)
end
@ -88,7 +82,6 @@ module CouchRest
design_doc['views'][view_name.to_s] &&
design_doc['views'][view_name.to_s]["couchrest-defaults"]) || {}
view_options = default_view_options.merge(options)
view_options.delete(:database)
[design_doc, view_name, view_options]
end
@ -101,8 +94,6 @@ module CouchRest
raise ArgumentError, 'search_name is required' if search_name.nil?
search_options = options.clone
search_options.delete(:database)
[design_doc, search_name, search_options]
end
@ -137,9 +128,6 @@ module CouchRest
else
@view_name = "#{design_doc}/#{view_name}"
end
# Save the design doc, ready for use
@container_class.save_design_doc(@database)
end
# See Collection.paginate
@ -231,7 +219,7 @@ module CouchRest
if @container_class.nil?
results
else
results['rows'].collect { |row| @container_class.build_from_database(row['doc']) } unless results['rows'].nil?
results['rows'].collect { |row| @container_class.create_from_database(row['doc']) } unless results['rows'].nil?
end
end
@ -244,7 +232,6 @@ module CouchRest
else
options = { :limit => per_page, :skip => per_page * (page - 1) }
end
options[:include_docs] = true
view_options.merge(options)
end

View file

@ -1,67 +0,0 @@
module CouchRest
# CouchRest Model Configuration support, stolen from Carrierwave by jnicklas
# http://github.com/jnicklas/carrierwave/blob/master/lib/carrierwave/uploader/configuration.rb
module Model
module Configuration
extend ActiveSupport::Concern
included do
add_config :model_type_key
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|
config.model_type_key = 'type' # was 'couchrest-type'
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
module ClassMethods
def add_config(name)
class_eval <<-RUBY, __FILE__, __LINE__ + 1
def self.#{name}(value=nil)
@#{name} = value if value
return @#{name} if self.object_id == #{self.object_id} || defined?(@#{name})
name = superclass.#{name}
return nil if name.nil? && !instance_variable_defined?("@#{name}")
@#{name} = name && !name.is_a?(Module) && !name.is_a?(Symbol) && !name.is_a?(Numeric) && !name.is_a?(TrueClass) && !name.is_a?(FalseClass) ? name.dup : name
end
def self.#{name}=(value)
@#{name} = value
end
def #{name}
self.class.#{name}
end
RUBY
end
def configure
yield self
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

@ -2,18 +2,23 @@
module CouchRest
module Model
module DesignDoc
extend ActiveSupport::Concern
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def design_doc
@design_doc ||= if auto_update_design_doc
::CouchRest::Design.new(default_design_doc)
else
stored_design_doc || ::CouchRest::Design.new(default_design_doc)
end
@design_doc ||= Design.new(default_design_doc)
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
def design_doc_id
"_design/#{design_doc_slug}"
end
@ -22,89 +27,6 @@ module CouchRest
self.to_s
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
{
"_id" => design_doc_id,
@ -112,7 +34,7 @@ module CouchRest
"views" => {
'all' => {
'map' => "function(doc) {
if (doc['#{self.model_type_key}'] == '#{self.to_s}') {
if (doc['couchrest-type'] == '#{self.to_s}') {
emit(doc['_id'],1);
}
}"
@ -121,8 +43,84 @@ module CouchRest
}
end
end # module ClassMethods
# 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
end
end

View file

@ -1,91 +0,0 @@
#### NOTE Work in progress! Not yet used!
module CouchRest
module Model
# A design block in CouchRest Model groups together the functionality of CouchDB's
# design documents in a simple block definition.
#
# class Person < CouchRest::Model::Base
# property :name
# timestamps!
#
# design do
# view :by_name
# end
# end
#
module Designs
extend ActiveSupport::Concern
module ClassMethods
# Add views and other design document features
# to the current model.
def design(*args, &block)
mapper = DesignMapper.new(self)
mapper.create_view_method(:all)
mapper.instance_eval(&block) if block_given?
end
# Override the default page pagination value:
#
# class Person < CouchRest::Model::Base
# paginates_per 10
# end
#
def paginates_per(val)
@_default_per_page = val
end
# The models number of documents to return
# by default when performing pagination.
# Returns 25 unless explicitly overridden via <tt>paginates_per</tt>
def default_per_page
@_default_per_page || 25
end
end
#
class DesignMapper
attr_accessor :model
def initialize(model)
self.model = model
end
# Generate a method that will provide a new View instance when
# requested. This will also define the view in CouchDB unless
# auto_update_design_doc is disabled.
def view(name, opts = {})
View.create(model, name, opts) if model.auto_update_design_doc
create_view_method(name)
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)
model.class_eval <<-EOS, __FILE__, __LINE__ + 1
def self.#{name}(opts = {})
CouchRest::Model::Designs::View.new(self, opts, '#{name}')
end
EOS
end
end
end
end
end

View file

@ -1,513 +0,0 @@
module CouchRest
module Model
module Designs
#
# A proxy class that allows view queries to be created using
# chained method calls. After each call a new instance of the method
# is created based on the original in a similar fashion to ruby's Sequel
# library, or Rails 3's Arel.
#
# CouchDB views have inherent limitations, so joins and filters as used in
# a normal relational database are not possible.
#
class View
include Enumerable
attr_accessor :owner, :model, :name, :query, :result
# Initialize a new View object. This method should not be called from
# outside CouchRest Model.
def initialize(parent, new_query = {}, name = nil)
if parent.is_a?(Class) && parent < CouchRest::Model::Base
raise "Name must be provided for view to be initialized" if name.nil?
self.model = parent
self.owner = parent
self.name = name.to_s
# Default options:
self.query = { }
elsif parent.is_a?(self.class)
self.model = (new_query.delete(:proxy) || parent.model)
self.owner = parent.owner
self.name = parent.name
self.query = parent.query.dup
else
raise "View cannot be initialized without a parent Model or View"
end
query.update(new_query)
super()
end
# == View Execution Methods
#
# Request to the CouchDB database using the current query values.
# Return each row wrapped in a ViewRow object. Unlike the raw
# CouchDB request, this will provide an empty array if there
# are no results.
def rows
return @rows if @rows
if execute && result['rows']
@rows ||= result['rows'].map{|v| ViewRow.new(v, model)}
else
[ ]
end
end
# Fetch all the documents the view can access. If the view has
# not already been prepared for including documents in the query,
# it will be added automatically and reset any previously cached
# results.
def all
include_docs!
docs
end
# Provide all the documents from the view. If the view has not been
# prepared with the +include_docs+ option, each document will be
# loaded individually.
def docs
@docs ||= rows.map{|r| r.doc}
end
# If another request has been made on the view, this will return
# the first document in the set. If not, a new query object will be
# generated with a limit of 1 so that only the first document is
# loaded.
def first
result ? all.first : limit(1).all.first
end
# Same as first but will order the view in descending order. This
# does not however reverse the search keys or the offset, so if you
# are using a +startkey+ and +endkey+ you might end up with
# unexpected results.
#
# If in doubt, don't use this method!
#
def last
result ? all.last : limit(1).descending.all.last
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
# can be reduced, the reduce will be performed and return the first
# value. This is okay for most simple queries, but may provide
# unexpected results if your reduce method does not calculate
# the total number of documents in a result set.
#
# Trying to use this method with the group option will raise an error.
#
# If no reduce function is defined, a query will be performed
# to return the total number of rows, this is the equivalant of:
#
# view.limit(0).total_rows
#
def count
raise "View#count cannot be used with group options" if query[:group]
if can_reduce?
row = reduce.skip(0).limit(1).rows.first
row.nil? ? 0 : row.value
else
limit(0).total_rows
end
end
# Check to see if the array of documents is empty. This *will*
# perform the query and return all documents ready to use, if you don't
# want to load anything, use +#total_rows+ or +#count+ instead.
def empty?
all.empty?
end
# Run through each document provided by the +#all+ method.
# This is also used by the Enumerator mixin to provide all the standard
# ruby collection directly on the view.
def each(&block)
all.each(&block)
end
# Wrapper for the results offset. As per the CouchDB API,
# this may be nil if groups are used.
def offset
execute['offset']
end
# Wrapper for the total_rows value provided by the query. As per the
# CouchDB API, this may be nil if groups are used.
def total_rows
execute['total_rows']
end
# Convenience wrapper to provide all the values from the route
# set without having to go through +rows+.
def values
rows.map{|r| r.value}
end
# Accept requests as if the view was an array. Used for backwards compatibity
# with older queries:
#
# Model.all(:raw => true, :limit => 0)['total_rows']
#
# In this example, the raw option will be ignored, and the total rows
# will still be accessible.
#
def [](value)
execute[value]
end
# No yet implemented. Eventually this will provide a raw hash
# of the information CouchDB holds about the view.
def info
raise "Not yet implemented"
end
# == View Filter Methods
#
# View filters return a copy of the view instance with the query
# modified appropriatly. Errors will be raised if the methods
# are combined in an incorrect fashion.
#
# Find all entries in the index whose key matches the value provided.
#
# Cannot be used when the +#startkey+ or +#endkey+ have been set.
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?
update_query(:key => value)
end
# Find all index keys that start with the value provided. May or may
# not be used in conjunction with the +endkey+ option.
#
# When the +#descending+ option is used (not the default), the start
# and end keys should be reversed, as per the CouchDB API.
#
# Cannot be used if the key has been set.
def startkey(value)
raise "View#startkey cannot be used when key has been set" unless query[:key].nil? && query[:keys].nil?
update_query(:startkey => value)
end
# The result set should start from the position of the provided document.
# The value may be provided as an object that responds to the +#id+ call
# or a string.
def startkey_doc(value)
update_query(:startkey_docid => value.is_a?(String) ? value : value.id)
end
# The opposite of +#startkey+, finds all index entries whose key is before
# the value specified.
#
# See the +#startkey+ method for more details and the +#inclusive_end+
# option.
def endkey(value)
raise "View#endkey cannot be used when key has been set" unless query[:key].nil? && query[:keys].nil?
update_query(:endkey => value)
end
# The result set should end at the position of the provided document.
# The value may be provided as an object that responds to the +#id+
# call or a string.
def endkey_doc(value)
update_query(:endkey_docid => value.is_a?(String) ? value : value.id)
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. 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
# be undone once used, it has no inverse option.
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)
end
# Limit the result set to the value supplied.
def limit(value)
update_query(:limit => value)
end
# Skip the number of entries in the index specified by value. This would be
# the equivilent of an offset in SQL.
#
# The CouchDB documentation states that the skip option should not be used
# with large data sets as it is inefficient. Use the +startkey_doc+ method
# instead to skip ranges efficiently.
def skip(value = 0)
update_query(:skip => value)
end
# Use the reduce function on the view. If none is available this method
# will fail.
def reduce
raise "Cannot reduce a view without a reduce method" unless can_reduce?
update_query(:reduce => true, :include_docs => nil)
end
# Control whether the reduce function reduces to a set of distinct keys
# or to a single result row.
#
# By default the value is false, and can only be set when the view's
# +#reduce+ option has been set.
def group
raise "View#reduce must have been set before grouping is permitted" unless query[:reduce]
update_query(:group => true)
end
# Will set the level the grouping should be performed to. As per the
# CouchDB API, it only makes sense when the index key is an array.
#
# This will automatically set the group option.
def group_level(value)
group.update_query(:group_level => value.to_i)
end
def include_docs
update_query.include_docs!
end
### Special View Filter Methods
# Specify the database the view should use. If not defined,
# an attempt will be made to load its value from the model.
def database(value)
update_query(:database => value)
end
# Set the view's proxy that will be used instead of the model
# for any future searches. As soon as this enters the
# new object's initializer it will be removed and replace
# the model object.
#
# See the Proxyable mixin for more details.
#
def proxy(value)
update_query(:proxy => value)
end
# Return any cached values to their nil state so that any queries
# requested later will have a fresh set of data.
def reset!
self.result = nil
@rows = nil
@docs = nil
end
# == Kaminari compatible pagination support
#
# Based on the really simple support for scoped pagination in the
# the Kaminari gem, we provide compatible methods here to perform
# the same actions you'd expect.
#
def page(page)
limit(owner.default_per_page).skip(owner.default_per_page * ([page.to_i, 1].max - 1))
end
def per(num)
raise "View#page must be called before #per!" if limit_value.nil? || offset_value.nil?
if (n = num.to_i) <= 0
self
else
limit(num).skip(offset_value / limit_value * n)
end
end
def total_count
@total_count ||= limit(nil).skip(nil).count
end
def offset_value
query[:skip]
end
def limit_value
query[:limit]
end
def num_pages
(total_count.to_f / limit_value).ceil
end
def current_page
(offset_value / limit_value) + 1
end
protected
def include_docs!
raise "Cannot include documents in view that has been reduced!" if query[:reduce]
reset! if result && !include_docs?
query[:include_docs] = true
self
end
def include_docs?
!!query[:include_docs]
end
def update_query(new_query = {})
self.class.new(self, new_query)
end
def design_doc
model.design_doc
end
def can_reduce?
!design_doc['views'][name]['reduce'].blank?
end
def use_database
query[:database] || model.database
end
def execute
return self.result if result
raise "Database must be defined in model or view!" if use_database.nil?
# Remove the reduce value if its not needed to prevent CouchDB errors
query.delete(:reduce) unless can_reduce?
model.save_design_doc(use_database)
self.result = model.design_doc.view_on(use_database, name, query.reject{|k,v| v.nil?})
end
# Class Methods
class << self
# Simplified view creation. A new view will be added to the
# provided model's design document using the name and options.
#
# 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
# generated automatically. For example:
#
# View.create(Meeting, "by_date_and_name")
#
# Will create a view that searches by the date and name properties.
# Explicity setting the attributes to use is possible using the
# +:by+ option. For example:
#
# View.create(Meeting, "by_date_and_name", :by => [:date, :firstname, :lastname])
#
# The view name is the same, but three keys would be used in the
# 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 = {})
unless opts[:map]
if opts[:by].nil? && name.to_s =~ /^by_(.+)/
opts[:by] = $1.split(/_and_/)
end
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].push "(doc['#{model.model_type_key}'] == '#{model.to_s}')"
keys = opts[:by].map{|o| "doc['#{o}']"}
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} != '')"} unless opts[:allow_blank]
opts[:map] = <<-EOF
function(doc) {
if (#{opts[:guards].join(' && ')}) {
emit(#{emit}, 1);
}
}
EOF
opts[:reduce] = <<-EOF
function(key, values, rereduce) {
return sum(values);
}
EOF
end
model.design_doc['views'] ||= {}
view = model.design_doc['views'][name.to_s] = { }
view['map'] = opts[:map]
view['reduce'] = opts[:reduce] if opts[:reduce]
view
end
end
end
# A special wrapper class that provides easy access to the key
# fields in a result row.
class ViewRow < Hash
attr_reader :model
def initialize(hash, model)
@model = model
replace(hash)
end
def id
self["id"]
end
def key
self["key"]
end
def value
self['value']
end
def raw_doc
self['doc']
end
# Send a request for the linked document either using the "id" field's
# value, or the ["value"]["_id"] used for linked documents.
def doc
return model.build_from_database(self['doc']) if self['doc']
doc_id = (value.is_a?(Hash) && value['_id']) ? value['_id'] : self.id
doc_id ? model.get(doc_id) : nil
end
end
end
end
end

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,25 +1,28 @@
module CouchRest
module Model
module DocumentQueries
extend ActiveSupport::Concern
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
# Load all documents that have the model_type_key's field equal to the
# Load all documents that have the "couchrest-type" field equal to the
# name of the current class. Take the standard set of
# CouchRest::Database#view options.
def all(opts = {}, &block)
view(:all, opts, &block)
end
# Returns the number of documents that have the model_type_key's field
# Returns the number of documents that have the "couchrest-type" field
# equal to the name of the current class. Takes the standard set of
# CouchRest::Database#view options
def count(opts = {}, &block)
all({:raw => true, :limit => 0}.merge(opts), &block)['total_rows']
end
# Load the first document that have the model_type_key's field equal to
# Load the first document that have the "couchrest-type" field equal to
# the name of the current class.
#
# ==== Returns
@ -35,22 +38,6 @@ module CouchRest
first_instance.empty? ? nil : first_instance.first
end
# Load the last document that have the model_type_key's field equal to
# the name of the current class.
# It's similar to method first, just adds :descending => true
#
# ==== Returns
# Object:: The last object instance available
# or
# Nil:: if no instances available
#
# ==== Parameters
# opts<Hash>::
# View options, see <tt>CouchRest::Database#view</tt> options for more info.
def last(opts = {})
first(opts.merge!(:descending => true))
end
# Load a document from the database by id
# No exceptions will be raised if the document isn't found
#
@ -70,7 +57,7 @@ module CouchRest
end
end
alias :find :get
# Load a document from the database by id
# An exception will be raised if the document isn't found
#
@ -83,12 +70,8 @@ module CouchRest
# id<String, Integer>:: Document ID
# db<Database>:: optional option to pass a custom database to use
def get!(id, db = database)
raise CouchRest::Model::DocumentNotFound if id.blank?
doc = db.get id
build_from_database(doc)
rescue RestClient::ResourceNotFound
raise CouchRest::Model::DocumentNotFound
create_from_database(doc)
end
alias :find! :get!

View file

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

View file

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

View file

@ -3,7 +3,7 @@ module CouchRest
module Persistence
extend ActiveSupport::Concern
# Create the document. Validation is enabled by default and will return
# Create the document. Validation is enabled by default and will return
# false if the document is not valid. If all goes well, the document will
# be returned.
def create(options = {})
@ -12,41 +12,35 @@ module CouchRest
_run_save_callbacks do
set_unique_id if new? && self.respond_to?(:set_unique_id)
result = database.save_doc(self)
ret = (result["ok"] == true) ? self : false
@changed_attributes.clear if ret && @changed_attributes
ret
(result["ok"] == true) ? self : false
end
end
end
# Creates the document in the db. Raises an exception
# if the document is not created properly.
def create!(options = {})
self.class.fail_validate!(self) unless self.create(options)
def create!
self.class.fail_validate!(self) unless self.create
end
# Trigger the callbacks (before, after, around)
# only if the document isn't new
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 new?
raise "Calling #{self.class.name}#update on document that has not been created!" if self.new?
return false unless perform_validations(options)
return true if !self.disable_dirty && !self.changed?
_run_update_callbacks do
_run_save_callbacks do
result = database.save_doc(self)
ret = result["ok"] == true
@changed_attributes.clear if ret && @changed_attributes
ret
result["ok"] == true
end
end
end
# Trigger the callbacks (before, after, around) and save the document
def save(options = {})
self.new? ? create(options) : update(options)
end
# Saves the document to the db using save. Raises an exception
# if the document is not saved properly.
def save!
@ -55,48 +49,20 @@ module CouchRest
end
# 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
_run_destroy_callbacks do
result = database.delete_doc(self)
if result['ok']
@_destroyed = true
self.freeze
self.delete('_rev')
self.delete('_id')
end
result['ok']
end
end
def destroyed?
!!@_destroyed
end
def persisted?
!new? && !destroyed?
end
# Update the document's attributes and save. For example:
#
# doc.update_attributes :name => "Fred"
# Is the equivilent of doing the following:
#
# doc.attributes = { :name => "Fred" }
# doc.save
#
def update_attributes(hash)
update_attributes_without_saving hash
save
end
# Reloads the attributes of this object from the database.
# It doesn't override custom instance variables.
#
# Returns self.
def reload
prepare_all_attributes(database.get(id), :directly_set_attributes => true)
self
end
protected
protected
def perform_validations(options = {})
perform_validation = case options
@ -111,35 +77,32 @@ module CouchRest
module ClassMethods
# Creates a new instance, bypassing attribute protection and
# uses the type field to determine which model to use to instanatiate
# the new object.
# Creates a new instance, bypassing attribute protection
#
#
# ==== Returns
# a document instance
#
def build_from_database(doc = {}, options = {}, &block)
src = doc[model_type_key]
base = (src.blank? || src == self.to_s) ? self : src.constantize
base.new(doc, options.merge(:directly_set_attributes => true), &block)
def create_from_database(doc = {})
base = (doc['couchrest-type'].blank? || doc['couchrest-type'] == self.to_s) ? self : doc['couchrest-type'].constantize
base.new(doc, :directly_set_attributes => true)
end
# Defines an instance and save it directly to the database
#
# Defines an instance and save it directly to the database
#
# ==== Returns
# returns the reloaded document
def create(attributes = {}, &block)
instance = new(attributes, &block)
def create(attributes = {})
instance = new(attributes)
instance.create
instance
end
# Defines an instance and save it directly to the database
#
# Defines an instance and save it directly to the database
#
# ==== Returns
# returns the reloaded document or raises an exception
def create!(attributes = {}, &block)
instance = new(attributes, &block)
def create!(attributes = {})
instance = new(attributes)
instance.create!
instance
end
@ -152,7 +115,7 @@ module CouchRest
# must be globally unique across all document types which share a
# database, so if you'd like to scope uniqueness to this class, you
# 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
define_method :set_unique_id do
self['_id'] ||= self.send(method)
@ -171,7 +134,7 @@ module CouchRest
raise Errors::Validations.new(document)
end
end
end
end

View file

@ -2,135 +2,47 @@
module CouchRest
module Model
module Properties
extend ActiveSupport::Concern
included do
class_attribute(:properties) unless self.respond_to?(:properties)
class_attribute(:properties_by_name) unless self.respond_to?(:properties_by_name)
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?(:[]=))
class IncludeError < StandardError; end
def self.included(base)
base.class_eval <<-EOS, __FILE__, __LINE__ + 1
extlib_inheritable_accessor(:properties) unless self.respond_to?(:properties)
self.properties ||= []
EOS
base.extend(ClassMethods)
raise CouchRest::Mixins::Properties::IncludeError, "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 (base.new.respond_to?(:[]) && base.new.respond_to?(:[]=))
end
# Provide an attribute hash ready to be sent to CouchDB but with
# all the nil attributes removed.
def as_couch_json
super.delete_if{|k,v| v.nil?}
end
# Returns the Class properties with their values
# Returns the Class properties
#
# ==== Returns
# Array:: the list of properties with their values
def properties_with_values
props = {}
properties.each { |property| props[property.name] = read_attribute(property.name) }
props
# Array:: the list of properties for model's class
def properties
self.class.properties
end
# Read the casted value of an attribute defined with a property.
#
# ==== Returns
# Object:: the casted attibutes value.
def read_attribute(property)
self[find_property!(property).to_s]
self[property.to_s]
end
# Store a casted value in the current instance of an attribute defined
# with a property and update dirty status
def write_attribute(property, value)
prop = find_property!(property)
value = 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
prop = property.is_a?(Property) ? property : self.class.properties.detect {|p| p.to_s == property.to_s}
raise "Missing property definition for #{property.to_s}" unless prop
self[prop.to_s] = prop.cast(self, value)
end
# Takes a hash as argument, and applies the values by using writer methods
# for each key. It doesn't save the document at the end. Raises a NoMethodError if the corresponding methods are
# missing. In case of error, no attributes are changed.
def update_attributes_without_saving(hash)
# Remove any protected and update all the rest. Any attributes
# which do not have a property will simply be ignored.
attrs = remove_protected_attributes(hash)
directly_set_attributes(attrs)
end
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
# The following methods should be accessable by the Model::Base Class, but not by anything else!
def apply_all_property_defaults
return if self.respond_to?(:new?) && (new? == false)
# 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|
write_attribute(property, property.default_value)
end
self.disable_dirty = dirty
end
def prepare_all_attributes(attrs = {}, options = {})
self.disable_dirty = !!options[:directly_set_attributes]
apply_all_property_defaults
if options[:directly_set_attributes]
directly_set_read_only_attributes(attrs)
directly_set_attributes(attrs, true)
else
attrs = remove_protected_attributes(attrs)
directly_set_attributes(attrs)
end
self.disable_dirty = false
self
end
def find_property!(property)
prop = find_property(property)
raise ArgumentError, "Missing property definition for #{property.to_s}" if prop.nil?
prop
end
# Set all the attributes and return a hash with the attributes
# that have not been accepted.
def directly_set_attributes(hash, mass_assign = false)
return if hash.nil?
hash.reject do |key, value|
if self.respond_to?("#{key}=")
self.send("#{key}=", value)
elsif mass_assign || mass_assign_any_attribute
self[key] = value
end
end
end
def directly_set_read_only_attributes(hash)
property_list = self.properties.map{|p| p.name}
hash.each do |attribute_name, attribute_value|
next if self.respond_to?("#{attribute_name}=")
if property_list.include?(attribute_name)
write_attribute(attribute_name, hash.delete(attribute_name))
end
end
end
module ClassMethods
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 = { }
type = options.shift
if type.class != Hash
@ -146,83 +58,87 @@ module CouchRest
end
# Automatically set <tt>updated_at</tt> and <tt>created_at</tt> fields
# on the document whenever saving occurs.
#
# These properties are casted as Time objects, so they should always
# be set to UTC.
# on the document whenever saving occurs. CouchRest uses a pretty
# decent time format by default. See Time#to_json
def timestamps!
property(:updated_at, Time, :read_only => true, :protected => true, :auto_validation => false)
property(:created_at, Time, :read_only => true, :protected => true, :auto_validation => false)
set_callback :save, :before do |object|
write_attribute('updated_at', Time.now)
write_attribute('created_at', Time.now) if object.new?
end
class_eval <<-EOS, __FILE__, __LINE__
property(:updated_at, Time, :read_only => true, :protected => true, :auto_validation => false)
property(:created_at, Time, :read_only => true, :protected => true, :auto_validation => false)
set_callback :save, :before do |object|
write_attribute('updated_at', Time.now)
write_attribute('created_at', Time.now) if object.new?
end
EOS
end
protected
# This is not a thread safe operation, if you have to set new properties at runtime
# make sure a mutex is used.
def define_property(name, options={}, &block)
# check if this property is going to casted
type = options.delete(:type) || options.delete(:cast_as)
if block_given?
type = Class.new do
include Embeddable
end
if block.arity == 1 # Traditional, with options
type.class_eval { yield type }
else
type.instance_exec(&block)
type = Class.new(Hash) do
include CastedModel
end
type.class_eval { yield type }
type = [type] # inject as an array
end
property = Property.new(name, type, options)
create_property_getter(property)
create_property_getter(property)
create_property_setter(property) unless property.read_only == true
if property.type_class.respond_to?(:validates_casted_model)
validates_casted_model property.name
end
properties << property
properties_by_name[property.to_s] = property
property
end
# defines the getter for the property (and optional aliases)
def create_property_getter(property)
define_method(property.name) do
read_attribute(property.name)
end
# meth = property.name
class_eval <<-EOS, __FILE__, __LINE__ + 1
def #{property.name}
read_attribute('#{property.name}')
end
EOS
if ['boolean', TrueClass.to_s.downcase].include?(property.type.to_s.downcase)
define_method("#{property.name}?") do
value = read_attribute(property.name)
!(value.nil? || value == false)
end
class_eval <<-EOS, __FILE__, __LINE__
def #{property.name}?
value = read_attribute('#{property.name}')
!(value.nil? || value == false)
end
EOS
end
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
# defines the setter for the property (and optional aliases)
def create_property_setter(property)
name = property.name
define_method("#{name}=") do |value|
write_attribute(name, value)
end
property_name = property.name
class_eval <<-EOS
def #{property_name}=(value)
write_attribute('#{property_name}', value)
end
EOS
if property.alias
alias_method "#{property.alias}=", "#{name}="
class_eval <<-EOS
alias #{property.alias.to_sym}= #{property_name.to_sym}=
EOS
end
end
end # module ClassMethods
end
end
end

View file

@ -27,24 +27,28 @@ module CouchRest::Model
if value.nil?
value = []
elsif [Hash, HashWithIndifferentAccess].include?(value.class)
# Assume provided as a params hash where key is index
value = parameter_hash_to_array(value)
elsif !value.is_a?(Array)
# Assume provided as a Hash where key is index!
data = value
value = [ ]
data.keys.sort.each do |k|
value << data[k]
end
elsif value.class != Array
raise "Expecting an array or keyed hash for property #{parent.class.name}##{self.name}"
end
arr = value.collect { |data| cast_value(parent, data) }
# allow casted_by calls to be passed up chain by wrapping in CastedArray
CastedArray.new(arr, self, parent)
elsif (type == Object || type == Hash) && (value.is_a?(Hash))
# allow casted_by calls to be passed up chain by wrapping in CastedHash
CastedHash[value, self, parent]
value = type_class != String ? CastedArray.new(arr, self) : arr
value.casted_by = parent if value.respond_to?(:casted_by)
elsif !value.nil?
cast_value(parent, value)
value = cast_value(parent, value)
end
value
end
# Cast an individual value
# Cast an individual value, not an array
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)
associate_casted_value_to_parent(parent, value)
end
@ -54,48 +58,26 @@ module CouchRest::Model
if default.class == Proc
default.call
else
# TODO identify cause of mutex errors
Marshal.load(Marshal.dump(default))
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
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)
value.casted_by = parent if value.respond_to?(:casted_by)
value.casted_by_property = self if value.respond_to?(:casted_by_property)
value
end
def parse_type(type)
if type.nil?
@casted = false
@type = nil
@type = nil
@type_class = nil
else
base = type.is_a?(Array) ? type.first : type
base = Object if base.nil?
raise "Defining a property type as a #{type.class.name.humanize} is not supported in CouchRest Model!" if base.class != Class
raise "Defining a property type as a #{type.class.name.humanize} is not supported in CouchRest Model!" if base.class != Class
@type_class = base
@type = type
end

View file

@ -1,71 +0,0 @@
module CouchRest
module Model
module PropertyProtection
extend ActiveSupport::Concern
# Property protection from mass assignment to CouchRest::Model properties
#
# Protected methods will be removed from
# * new
# * update_attributes
# * upate_attributes_without_saving
# * attributes=
#
# There are two modes of protection
# 1) Declare accessible poperties, and assume all unspecified properties are protected
# property :name, :accessible => true
# property :admin # this will be automatically protected
#
# 2) Declare protected properties, and assume all unspecified properties are accessible
# property :name # this will not be protected
# property :admin, :protected => true
#
# 3) Mix and match, and assume all unspecified properties are protected.
# property :name, :accessible => true
# property :admin, :protected => true # ignored
# property :phone # this will be automatically protected
#
# Note: the timestamps! method protectes the created_at and updated_at properties
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def accessible_properties
props = properties.select { |prop| prop.options[:accessible] }
if props.empty?
props = properties.select { |prop| !prop.options[:protected] }
end
props
end
def protected_properties
accessibles = accessible_properties
properties.reject { |prop| accessibles.include?(prop) }
end
end
def accessible_properties
self.class.accessible_properties
end
def protected_properties
self.class.protected_properties
end
# Return a new copy of the attributes hash with protected attributes
# removed.
def remove_protected_attributes(attributes)
protected_names = protected_properties.map { |prop| prop.name }
return attributes if protected_names.empty? or attributes.nil?
attributes.reject do |property_name, property_value|
protected_names.include?(property_name.to_s)
end
end
end
end
end

View file

@ -1,183 +0,0 @@
module CouchRest
module Model
# :nodoc: Because I like inventing words
module Proxyable
extend ActiveSupport::Concern
def proxy_database
raise StandardError, "Please set the #proxy_database_method" if self.class.proxy_database_method.nil?
@proxy_database ||= self.class.prepare_database(self.send(self.class.proxy_database_method))
end
module ClassMethods
# Define a collection that will use the base model for the database connection
# details.
def proxy_for(assoc_name, options = {})
db_method = options[:database_method] || "proxy_database"
options[:class_name] ||= assoc_name.to_s.singularize.camelize
class_eval <<-EOS, __FILE__, __LINE__ + 1
def #{assoc_name}
@#{assoc_name} ||= CouchRest::Model::Proxyable::ModelProxy.new(::#{options[:class_name]}, self, self.class.to_s.underscore, #{db_method})
end
EOS
end
# Tell this model which other model to use a base for the database
# connection to use.
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?
self.proxy_owner_method = model_name
attr_accessor :model_proxy
attr_accessor model_name
overwrite_database_reader(model_name)
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
class ModelProxy
attr_reader :model, :owner, :owner_name, :database
def initialize(model, owner, owner_name, database)
@model = model
@owner = owner
@owner_name = owner_name
@database = database
end
# Base
def new(attrs = {}, options = {}, &block)
proxy_block_update(:new, attrs, options, &block)
end
def build_from_database(attrs = {}, options = {}, &block)
proxy_block_update(:build_from_database, attrs, options, &block)
end
def method_missing(m, *args, &block)
if has_view?(m)
if model.respond_to?(m)
return model.send(m, *args).proxy(self)
else
query = args.shift || {}
return view(m, query, *args, &block)
end
elsif m.to_s =~ /^find_(by_.+)/
view_name = $1
if has_view?(view_name)
return first_from_view(view_name, *args)
end
end
super
end
# DocumentQueries
def all(opts = {}, &block)
proxy_update_all(@model.all({:database => @database}.merge(opts), &block))
end
def count(opts = {})
@model.count({:database => @database}.merge(opts))
end
def first(opts = {})
proxy_update(@model.first({:database => @database}.merge(opts)))
end
def last(opts = {})
proxy_update(@model.last({:database => @database}.merge(opts)))
end
def get(id)
proxy_update(@model.get(id, @database))
end
alias :find :get
# Views
def has_view?(view)
@model.has_view?(view)
end
def view_by(*args)
@model.view_by(*args)
end
def view(name, query={}, &block)
proxy_update_all(@model.view(name, {:database => @database}.merge(query), &block))
end
def first_from_view(name, *args)
# add to first hash available, or add to end
(args.last.is_a?(Hash) ? args.last : (args << {}).last)[:database] = @database
proxy_update(@model.first_from_view(name, *args))
end
# DesignDoc
def design_doc
@model.design_doc
end
def save_design_doc(db = nil)
@model.save_design_doc(db || @database)
end
protected
# Update the document's proxy details, specifically, the fields that
# link back to the original document.
def proxy_update(doc)
if doc && doc.is_a?(model)
doc.database = @database
doc.model_proxy = self
doc.send("#{owner_name}=", owner)
end
doc
end
def proxy_update_all(docs)
docs.each do |doc|
proxy_update(doc)
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

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,22 @@
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
# $7 = time zone direction
# $8 = tz difference
# utc time with wrong TZ info:
time = mktime($1, RFC2822_MONTH_NAME[$2.to_i - 1], $3, $4, $5, $6, $7)
tz_difference = ("#{$7 == '-' ? '+' : '-'}#{$8}".to_i * 3600)
time + tz_difference + zone_offset(time.zone)
end
end
module CouchRest
module Model
module Typecast
@ -6,15 +25,12 @@ module CouchRest
return nil if value.nil?
klass = property.type_class
if value.instance_of?(klass) || klass == Object
if klass == Time && !value.utc?
value.utc # Ensure Time is always in UTC
else
value
end
value
elsif [String, TrueClass, Integer, Float, BigDecimal, DateTime, Time, Date, Class].include?(klass)
send('typecast_to_'+klass.to_s.downcase, value)
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
@ -59,7 +75,7 @@ module CouchRest
# Match numeric string
def typecast_to_numeric(value, method)
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.to_str =~ /\A(-?(?:0|[1-9]\d*)(?:\.\d+)?|(?:\.\d+))\z/
$1.send(method)
else
value
@ -107,7 +123,7 @@ module CouchRest
if value.is_a?(Hash)
typecast_hash_to_time(value)
else
Time.parse_iso8601(value.to_s)
Time.mktime_with_offset(value.to_s)
end
rescue ArgumentError
value
@ -129,13 +145,13 @@ module CouchRest
# Creates a Time instance from a Hash with keys :year, :month, :day,
# :hour, :min, :sec
def typecast_hash_to_time(value)
Time.utc(*extract_time(value))
Time.local(*extract_time(value))
end
# Extracts the given args from the hash. If a value does not exist, it
# uses the value of Time.now.
def extract_time(value)
now = Time.now
now = Time.now
[:year, :month, :day, :hour, :min, :sec].map do |segment|
typecast_to_numeric(value.fetch(segment, now.send(segment)), :to_i)
end

View file

@ -13,33 +13,21 @@ module CouchRest
# Validations may be applied to both Model::Base and Model::CastedModel
module Validations
extend ActiveSupport::Concern
include ActiveModel::Validations
# 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)
included do
include ActiveModel::Validations
end
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
# is used inside the model.
#
def validates_casted_model(*args)
validates_with(CastedModelValidator, _merge_attributes(args))
end
# Validates if the field is unique for this type of document. Automatically creates
# a view if one does not already exist and performs a search for all matching
# documents.

View file

@ -6,9 +6,7 @@ module CouchRest
def validate_each(document, attribute, value)
values = value.is_a?(Array) ? value : [value]
return if values.collect {|doc| doc.nil? || doc.valid? }.all?
error_options = { :value => value }
error_options[:message] = options[:message] if options[:message]
document.errors.add(attribute, :invalid, error_options)
document.errors.add(attribute, :invalid, :default => options[:message], :value => value)
end
end
end

View file

@ -1,5 +1,5 @@
en:
errors:
messages:
taken: "has already been taken"
taken: "is already taken"

View file

@ -3,64 +3,39 @@
module CouchRest
module Model
module Validations
# Validates if a field is unique
class UniquenessValidator < ActiveModel::EachValidator
# Ensure we have a class available so we can check for a usable view
# or add one if necessary.
def setup(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
def setup(klass)
@klass = klass
end
def validate_each(document, attribute, value)
opts = merge_view_options(attribute)
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)
view_name = options[:view].nil? ? "by_#{attribute}" : options[:view]
# Determine the base of the search
base = opts[:proxy].nil? ? model : document.instance_eval(opts[:proxy])
base = options[:proxy].nil? ? @klass : document.instance_eval(options[:proxy])
if base.respond_to?(:has_view?) && !base.has_view?(opts[:view_name])
raise "View #{document.class.name}.#{opts[:view_name]} does not exist for validation!"
if base.respond_to?(:has_view?) && !base.has_view?(view_name)
raise "View #{document.class.name}.#{options[:view]} does not exist!" unless options[:view].nil?
@klass.view_by attribute
end
rows = base.view(opts[:view_name], :key => values, :limit => 2, :include_docs => false)['rows']
return if rows.empty?
docs = base.view(view_name, :key => value, :limit => 2, :include_docs => false)['rows']
return if docs.empty?
unless document.new?
return if rows.find{|row| row['id'] == document.id}
return if docs.find{|doc| doc['id'] == document.id}
end
if rows.length > 0
opts = options.merge(:value => value)
opts.delete(:scope) # Has meaning with I18n!
document.errors.add(attribute, :taken, opts)
if docs.length > 0
document.errors.add(attribute, :taken, :default => options[:message], :value => value)
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

View file

@ -2,7 +2,7 @@ module CouchRest
module Model
module Views
extend ActiveSupport::Concern
module ClassMethods
# Define a CouchDB view. The name of the view will be the concatenation
# of <tt>by</tt> and the keys joined by <tt>_and_</tt>
@ -23,7 +23,7 @@ module CouchRest
# view_by :tags,
# :map =>
# "function(doc) {
# if (doc['model'] == 'Post' && doc.tags) {
# if (doc['couchrest-type'] == 'Post' && doc.tags) {
# doc.tags.forEach(function(tag){
# emit(doc.tag, 1);
# });
@ -39,7 +39,7 @@ module CouchRest
# function:
#
# function(doc) {
# if (doc['model'] == 'Post' && doc.date) {
# if (doc['couchrest-type'] == 'Post' && doc.date) {
# emit(doc.date, null);
# }
# }
@ -72,38 +72,31 @@ module CouchRest
# <tt>spec/couchrest/more/extended_doc_spec.rb</tt>.
def view_by(*keys)
return unless auto_update_design_doc
opts = keys.pop if keys.last.is_a?(Hash)
opts ||= {}
ducktype = opts.delete(:ducktype)
unless ducktype || opts[:map]
opts[:guards] ||= []
opts[:guards].push "(doc['#{model_type_key}'] == '#{self.to_s}')"
opts[:guards].push "(doc['couchrest-type'] == '#{self.to_s}')"
end
keys.push opts
design_doc.view_by(*keys)
req_design_doc_refresh
end
# returns stored defaults if there is a view named this in the design doc
def has_view?(name)
design_doc && design_doc.has_view?(name)
end
# Check if the view can be reduced by checking to see if it has a
# reduce function.
def can_reduce_view?(name)
design_doc && design_doc.can_reduce_view?(name)
def has_view?(view)
view = view.to_s
design_doc && design_doc['views'] && design_doc['views'][view]
end
# Dispatches to any named view.
def view(name, query={}, &block)
query = query.dup # Modifications made on copy!
db = query.delete(:database) || database
query[:raw] = true if query[:reduce]
refresh_design_doc(db)
query[:raw] = true if query[:reduce]
raw = query.delete(:raw)
save_design_doc(db)
fetch_view_with_docs(db, name, query, raw, &block)
end
@ -134,18 +127,34 @@ module CouchRest
if raw || (opts.has_key?(:include_docs) && opts[:include_docs] == false)
fetch_view(db, name, opts, &block)
else
opts = opts.merge(:include_docs => true)
view = fetch_view db, name, opts, &block
view['rows'].collect{|r| build_from_database(r['doc'])} if view['rows']
if block.nil?
collection_proxy_for(design_doc, name, opts.merge({:database => db, :include_docs => true}))
else
view = fetch_view db, name, opts.merge({:include_docs => true}), &block
view['rows'].collect{|r|create_from_database(r['doc'])} if view['rows']
end
end
end
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
design_doc.view_on(db, view_name, opts, &block)
retryable = true
begin
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 # module ClassMethods
end
end
end

View file

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

View file

@ -1,17 +1,25 @@
gem 'couchrest', ">= 1.0.0.beta"
require 'couchrest'
gem "tzinfo", ">= 0.3.22"
gem "activesupport", ">= 2.3.5"
require 'active_support/core_ext'
require 'active_support/json'
gem "activemodel", ">= 3.0.0.beta4"
require 'active_model'
require "active_model/callbacks"
require "active_model/conversion"
require "active_model/deprecated_error_methods"
require "active_model/errors"
require "active_model/naming"
require "active_model/serialization"
require "active_model/translation"
require "active_model/validator"
require "active_model/validations"
require "active_model/dirty"
require 'active_support/core_ext'
require 'active_support/json'
gem "mime-types", ">= 1.15"
require 'mime/types'
require "enumerator"
require "time"
@ -20,19 +28,13 @@ require 'digest/md5'
require 'bigdecimal' # used in typecast
require 'bigdecimal/util' # used in typecast
require 'couchrest'
require 'couchrest/model'
require 'couchrest/model/errors'
require "couchrest/model/persistence"
require "couchrest/model/typecast"
require "couchrest/model/casted_by"
require "couchrest/model/dirty"
require "couchrest/model/property"
require "couchrest/model/property_protection"
require "couchrest/model/properties"
require "couchrest/model/casted_array"
require "couchrest/model/casted_hash"
require "couchrest/model/properties"
require "couchrest/model/validations"
require "couchrest/model/callbacks"
require "couchrest/model/document_queries"
@ -40,27 +42,18 @@ require "couchrest/model/views"
require "couchrest/model/design_doc"
require "couchrest/model/extended_attachments"
require "couchrest/model/class_proxy"
require "couchrest/model/proxyable"
require "couchrest/model/collection"
require "couchrest/model/attribute_protection"
require "couchrest/model/attributes"
require "couchrest/model/associations"
require "couchrest/model/configuration"
require "couchrest/model/connection"
require "couchrest/model/designs"
require "couchrest/model/designs/view"
# Monkey patches applied to couchrest
require "couchrest/model/support/couchrest_design"
require "couchrest/model/support/couchrest_database"
# Core Extensions
require "couchrest/model/core_extensions/hash"
require "couchrest/model/core_extensions/time_parsing"
require "couchrest/model/support/couchrest"
require "couchrest/model/support/hash"
# Base libraries
require "couchrest/model/embeddable"
require "couchrest/model/casted_model"
require "couchrest/model/base"
# Add rails support *after* everything has loaded
if defined?(Rails)
require "couchrest/railtie"
end

View file

@ -1,16 +0,0 @@
require 'rails/generators/named_base'
require 'rails/generators/active_model'
require 'couchrest_model'
module CouchrestModel
module Generators
class Base < Rails::Generators::NamedBase #:nodoc:
# Set the current directory as base for the inherited generators.
def self.base_root
File.dirname(__FILE__)
end
end
end
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,27 +0,0 @@
require 'rails/generators/couchrest_model'
module CouchrestModel
module Generators
class ModelGenerator < Base
check_class_collision
def create_model_file
template 'model.rb', File.join('app/models', class_path, "#{file_name}.rb")
end
def create_module_file
return if class_path.empty?
template 'module.rb', File.join('app/models', "#{class_path.join('/')}.rb") if behavior == :invoke
end
hook_for :test_framework
protected
def parent_class_name
"CouchRest::Model::Base"
end
end
end
end

View file

@ -1,2 +0,0 @@
class <%= class_name %> < <%= parent_class_name.classify %>
end

View file

@ -1,41 +1,14 @@
# 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 ".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
before :each do
@invoice = SaleInvoice.create(:price => 2000)
@invoice = SaleInvoice.create(:price => "sam", :price => 2000)
@client = Client.create(:name => "Sam Lown")
end
@ -70,6 +43,14 @@ describe "Assocations" do
@invoice.client
end
it "should raise error if class name does not exist" do
lambda {
class TestBadAssoc < CouchRest::Model::Base
belongs_to :test_bad_item
end
}.should raise_error
end
it "should allow override of foreign key" do
@invoice.respond_to?(:alternate_client).should be_true
@invoice.respond_to?("alternate_client=").should be_true
@ -88,7 +69,7 @@ describe "Assocations" do
describe "of type collection_of" do
before(:each) do
@invoice = SaleInvoice.create(:price => 2000)
@invoice = SaleInvoice.create(:price => "sam", :price => 2000)
@entries = [
SaleEntry.create(:description => 'test line 1', :price => 500),
SaleEntry.create(:description => 'test line 2', :price => 500),
@ -97,9 +78,9 @@ describe "Assocations" do
end
it "should create an associated property and collection proxy" do
@invoice.respond_to?('entry_ids').should be_true
@invoice.respond_to?('entry_ids=').should be_true
@invoice.entries.class.should eql(::CouchRest::Model::CollectionOfProxy)
@invoice.respond_to?('entry_ids')
@invoice.respond_to?('entry_ids=')
@invoice.entries.class.should eql(::CouchRest::CollectionOfProxy)
end
it "should allow replacement of objects" do
@ -115,7 +96,7 @@ describe "Assocations" do
@invoice.entries.length.should eql(3)
@invoice.entries.first.should eql(@entries.first)
end
it "should replace collection if ids replaced" do
@invoice.entry_ids = @entries.collect{|i| i.id}
@invoice.entries.length.should eql(3) # load once
@ -129,7 +110,7 @@ describe "Assocations" do
@invoice.entry_ids << @entries[2].id
@invoice.entry_ids.length.should eql(3)
@invoice.entries.length.should eql(2) # cached!
@invoice.entries(true).length.should eql(3)
@invoice.entries(true).length.should eql(3)
end
it "should empty arrays when nil collection provided" do
@ -152,35 +133,8 @@ describe "Assocations" do
@invoice.entries.should be_empty
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
it "should ensure new entries to proxy are matched" do
@invoice.entries << @entries.first
@invoice.entry_ids.first.should eql(@entries.first.id)
@ -223,7 +177,7 @@ describe "Assocations" do
@invoice.entries.first.should eql(@entries[1])
@invoice.entry_ids.first.should eql(@entries[1].id)
end
it "should raise error when adding un-persisted entries" do
SaleEntry.find_by_description('test entry').should be_nil
entry = SaleEntry.new(:description => 'test entry', :price => 500)

View file

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

View file

@ -1,4 +1,4 @@
require "spec_helper"
require File.expand_path("../../spec_helper", __FILE__)
describe "Model Attributes" do
@ -23,23 +23,17 @@ describe "Model Attributes" do
user.name.should == "will"
user.phone.should == "555-5555"
end
it "should recreate from the database properly" do
user = NoProtection.new
user.name = "will"
user.phone = "555-5555"
user.save!
user = NoProtection.get(user.id)
user.name.should == "will"
user.phone.should == "555-5555"
end
it "should provide a list of all properties as accessible" do
user = NoProtection.new(:name => "will", :phone => "555-5555")
user.accessible_properties.length.should eql(2)
user.protected_properties.should be_empty
end
end
describe "Model Base", "accessible flag" do
@ -49,8 +43,6 @@ describe "Model Attributes" do
property :admin, :default => false
end
it { expect { WithAccessible.new(nil) }.to_not raise_error }
it "should recognize accessible properties" do
props = WithAccessible.accessible_properties.map { |prop| prop.name}
props.should include("name")
@ -58,7 +50,7 @@ describe "Model Attributes" do
end
it "should protect non-accessible properties set through new" do
user = WithAccessible.new(:name => "will", :admin => true)
user = WithAccessible.new(:name => "will", :admin => true)
user.name.should == "will"
user.admin.should == false
@ -71,12 +63,6 @@ describe "Model Attributes" do
user.name.should == "will"
user.admin.should == false
end
it "should provide correct accessible and protected property lists" do
user = WithAccessible.new(:name => 'will', :admin => true)
user.accessible_properties.map{|p| p.to_s}.should eql(['name'])
user.protected_properties.map{|p| p.to_s}.should eql(['admin'])
end
end
describe "Model Base", "protected flag" do
@ -86,8 +72,6 @@ describe "Model Attributes" do
property :admin, :default => false, :protected => true
end
it { expect { WithProtected.new(nil) }.to_not raise_error }
it "should recognize protected properties" do
props = WithProtected.protected_properties.map { |prop| prop.name}
props.should_not include("name")
@ -95,7 +79,7 @@ describe "Model Attributes" do
end
it "should protect non-accessible properties set through new" do
user = WithProtected.new(:name => "will", :admin => true)
user = WithProtected.new(:name => "will", :admin => true)
user.name.should == "will"
user.admin.should == false
@ -108,41 +92,18 @@ describe "Model Attributes" do
user.name.should == "will"
user.admin.should == false
end
it "should not modify the provided attribute hash" do
user = WithProtected.new
attrs = {:name => "will", :admin => true}
user.attributes = attrs
attrs[:admin].should be_true
attrs[:name].should eql('will')
end
it "should provide correct accessible and protected property lists" do
user = WithProtected.new(:name => 'will', :admin => true)
user.accessible_properties.map{|p| p.to_s}.should eql(['name'])
user.protected_properties.map{|p| p.to_s}.should eql(['admin'])
end
end
describe "Model Base", "mixing protected and accessible flags" do
class WithBothAndUnspecified < CouchRest::Model::Base
describe "protected flag" do
class WithBoth < CouchRest::Model::Base
use_database TEST_SERVER.default_database
property :name, :accessible => true
property :admin, :default => false, :protected => true
property :phone, :default => 'unset phone number'
end
it { expect { WithBothAndUnspecified.new }.to_not raise_error }
it 'should assume that any unspecified property is protected by default' do
user = WithBothAndUnspecified.new(:name => 'will', :admin => true, :phone => '555-1234')
user.name.should == 'will'
user.admin.should == false
user.phone.should == 'unset phone number'
it "should raise an error when both are set" do
lambda { WithBoth.new }.should raise_error
end
end
describe "from database" do
@ -152,7 +113,7 @@ describe "Model Attributes" do
property :admin, :default => false, :protected => true
view_by :name
end
before(:each) do
@user = WithProtected.new
@user.name = "will"
@ -167,26 +128,26 @@ describe "Model Attributes" do
it "Base#get should not strip protected attributes" do
reloaded = WithProtected.get( @user.id )
verify_attrs reloaded
verify_attrs reloaded
end
it "Base#get! should not strip protected attributes" do
reloaded = WithProtected.get!( @user.id )
verify_attrs reloaded
verify_attrs reloaded
end
it "Base#all should not strip protected attributes" do
# all creates a CollectionProxy
docs = WithProtected.all(:key => @user.id)
docs.length.should == 1
docs.size.should == 1
reloaded = docs.first
verify_attrs reloaded
verify_attrs reloaded
end
it "views should not strip protected attributes" do
docs = WithProtected.by_name(:startkey => "will", :endkey => "will")
reloaded = docs.first
verify_attrs reloaded
verify_attrs reloaded
end
end
end

View file

@ -1,5 +1,11 @@
# 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
@ -28,60 +34,12 @@ describe "Model Base" do
@obj.should be_new_record
end
it "should not fail with nil argument" do
it "should not failed on a nil value in argument" do
@obj = Basic.new(nil)
@obj.should_not be_nil
end
it "should allow the database to be set" do
@obj = Basic.new(nil, :database => 'database')
@obj.database.should eql('database')
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")
@obj.should == { 'couchrest-type' => 'Basic' }
end
end
describe "ActiveModel compatability Basic" do
before(:each) do
@ -121,22 +79,14 @@ describe "Model Base" do
describe "#persisted?" do
context "when the document is new" do
it "returns false" do
@obj.persisted?.should be_false
@obj.persisted?.should == false
end
end
context "when the document is not new" do
it "returns id" do
@obj.save
@obj.persisted?.should be_true
end
end
context "when the document is destroyed" do
it "returns false" do
@obj.save
@obj.destroy
@obj.persisted?.should be_false
@obj.persisted?.should == true
end
end
end
@ -148,59 +98,9 @@ describe "Model Base" do
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
describe "update attributes without saving" do
before(:each) do
a = Article.get "big-bad-danger" rescue nil
@ -241,7 +141,7 @@ describe "Model Base" do
}.should_not raise_error
@art.slug.should == "big-bad-danger"
end
#it "should not change other attributes if there is an error" do
# lambda {
# @art.update_attributes_without_saving('slug' => "new-slug", :title => "super danger")
@ -249,7 +149,7 @@ describe "Model Base" do
# @art['title'].should == "big bad danger"
#end
end
describe "update attributes" do
before(:each) do
a = Article.get "big-bad-danger" rescue nil
@ -264,7 +164,7 @@ describe "Model Base" do
loaded['title'].should == "super danger"
end
end
describe "with default" do
it "should have the default value set at initalization" do
@obj.preset.should == {:right => 10, :top_align => false}
@ -284,14 +184,6 @@ describe "Model Base" do
obj = WithDefaultValues.new(:preset => 'test')
obj.preset = 'test'
end
it "should keep default values for new instances" do
obj = WithDefaultValues.new
obj.preset[:alpha] = 123
obj.preset.should == {:right => 10, :top_align => false, :alpha => 123}
another = WithDefaultValues.new
another.preset.should == {:right => 10, :top_align => false}
end
it "should work with a default empty array" do
obj = WithDefaultValues.new(:tags => ['spec'])
@ -318,10 +210,10 @@ describe "Model Base" do
describe "a doc with template values (CR::Model spec)" do
before(:all) do
WithTemplateAndUniqueID.all.map{|o| o.destroy}
WithTemplateAndUniqueID.all.map{|o| o.destroy(true)}
WithTemplateAndUniqueID.database.bulk_delete
@tmpl = WithTemplateAndUniqueID.new
@tmpl2 = WithTemplateAndUniqueID.new(:preset => 'not_value', 'slug' => '1')
@tmpl2 = WithTemplateAndUniqueID.new(:preset => 'not_value', 'important-field' => '1')
end
it "should have fields set when new" do
@tmpl.preset.should == 'value'
@ -340,12 +232,18 @@ describe "Model Base" do
describe "finding all instances of a model" do
before(:all) do
WithTemplateAndUniqueID.all.map{|o| o.destroy}
WithTemplateAndUniqueID.req_design_doc_refresh
WithTemplateAndUniqueID.all.map{|o| o.destroy(true)}
WithTemplateAndUniqueID.database.bulk_delete
WithTemplateAndUniqueID.new('slug' => '1').save
WithTemplateAndUniqueID.new('slug' => '2').save
WithTemplateAndUniqueID.new('slug' => '3').save
WithTemplateAndUniqueID.new('slug' => '4').save
WithTemplateAndUniqueID.new('important-field' => '1').save
WithTemplateAndUniqueID.new('important-field' => '2').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
it "should find all" do
rs = WithTemplateAndUniqueID.all
@ -356,6 +254,7 @@ describe "Model Base" do
describe "counting all instances of a model" do
before(:each) do
@db = reset_test_db!
WithTemplateAndUniqueID.req_design_doc_refresh
end
it ".count should return 0 if there are no docuemtns" do
@ -363,9 +262,9 @@ describe "Model Base" do
end
it ".count should return the number of documents" do
WithTemplateAndUniqueID.new('slug' => '1').save
WithTemplateAndUniqueID.new('slug' => '2').save
WithTemplateAndUniqueID.new('slug' => '3').save
WithTemplateAndUniqueID.new('important-field' => '1').save
WithTemplateAndUniqueID.new('important-field' => '2').save
WithTemplateAndUniqueID.new('important-field' => '3').save
WithTemplateAndUniqueID.count.should == 3
end
@ -374,14 +273,20 @@ describe "Model Base" do
describe "finding the first instance of a model" do
before(:each) do
@db = reset_test_db!
WithTemplateAndUniqueID.new('slug' => '1').save
WithTemplateAndUniqueID.new('slug' => '2').save
WithTemplateAndUniqueID.new('slug' => '3').save
WithTemplateAndUniqueID.new('slug' => '4').save
# WithTemplateAndUniqueID.req_design_doc_refresh # Removed by Sam Lown, design doc should be loaded automatically
WithTemplateAndUniqueID.new('important-field' => '1').save
WithTemplateAndUniqueID.new('important-field' => '2').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
it "should find first" do
rs = WithTemplateAndUniqueID.first
rs['slug'].should == "1"
rs['important-field'].should == "1"
end
it "should return nil if no instances are found" do
WithTemplateAndUniqueID.all.each {|obj| obj.destroy }
@ -389,6 +294,21 @@ describe "Model Base" do
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
before(:all) do
@ -444,7 +364,6 @@ describe "Model Base" do
foundart.created_at.should == foundart.updated_at
end
it "should set the time on update" do
@art.title = "new title" # only saved if @art.changed? == true
@art.save
@art.created_at.should < @art.updated_at
end
@ -459,7 +378,14 @@ describe "Model Base" do
end
end
describe "recursive validation on a model" do
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
before :each do
reset_test_db!
@cat = Cat.new(:name => 'Sockington')

View file

@ -1,46 +1,42 @@
# encoding: utf-8
require "spec_helper"
class WithCastedModelMixin
include CouchRest::Model::Embeddable
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', 'question')
require File.join(FIXTURE_PATH, 'more', 'course')
class WithCastedModelMixin < Hash
include CouchRest::Model::CastedModel
property :name
property :no_value
property :details, Object, :default => {}
property :casted_attribute, WithCastedModelMixin
end
class OldFashionedMixin < Hash
include CouchRest::Model::CastedModel
property :name
end
class DummyModel < CouchRest::Model::Base
use_database TEST_SERVER.default_database
raise "Default DB not set" if TEST_SERVER.default_database.nil?
property :casted_attribute, WithCastedModelMixin
property :keywords, [String]
property :old_casted_attribute, OldFashionedMixin
property :sub_models do |child|
child.property :title
end
property :param_free_sub_models do
property :title
end
end
class WithCastedCallBackModel
include CouchRest::Model::Embeddable
class WithCastedCallBackModel < Hash
include CouchRest::Model::CastedModel
property :name
property :run_before_validation
property :run_after_validation
validates_presence_of :run_before_validation
before_validation do |object|
object.run_before_validation = true
property :run_before_validate
property :run_after_validate
before_validate do |object|
object.run_before_validate = true
end
after_validation do |object|
object.run_after_validation = true
after_validate do |object|
object.run_after_validate = true
end
end
@ -50,48 +46,36 @@ class CastedCallbackDoc < CouchRest::Model::Base
property :callback_model, WithCastedCallBackModel
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
before(:each) do
@obj = WithCastedModelMixin.new
end
it "should automatically include the property mixin and define getters and setters" do
@obj.name = 'Matt'
@obj.name.should == 'Matt'
@obj.name.should == 'Matt'
end
it "should allow override of default" do
@obj = WithCastedModelMixin.new(:name => 'Eric', :details => {'color' => 'orange'})
@obj.name.should == 'Eric'
@obj.details['color'].should == 'orange'
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
describe "casted as an attribute, but without a value" do
before(:each) do
@obj = DummyModel.new
@ -114,39 +98,27 @@ describe CouchRest::Model::Embeddable do
@obj.sub_models << {:title => 'test'}
@obj.sub_models.first.title.should eql('test')
end
it "should be empty intitally (without params)" do
@obj.param_free_sub_models.should_not be_nil
@obj.param_free_sub_models.should be_empty
end
it "should be updatable using a hash (without params)" do
@obj.param_free_sub_models << {:title => 'test'}
@obj.param_free_sub_models.first.title.should eql('test')
end
end
describe "casted as attribute" do
before(:each) do
casted = {:name => 'not whatever'}
@obj = DummyModel.new(:casted_attribute => {:name => 'whatever', :casted_attribute => casted})
@casted_obj = @obj.casted_attribute
end
it "should be available from its parent" do
@casted_obj.should be_an_instance_of(WithCastedModelMixin)
end
it "should have the getters defined" do
@casted_obj.name.should == 'whatever'
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 == 'casted_attribute'}
end
it "should return nil for the 'no_value' attribute" do
@casted_obj.no_value.should be_nil
end
@ -154,59 +126,27 @@ describe CouchRest::Model::Embeddable do
it "should return nil for the unknown attribute" do
@casted_obj["unknown"].should be_nil
end
it "should return {} for the hash attribute" do
@casted_obj.details.should == {}
end
it "should cast its own attributes" do
@casted_obj.casted_attribute.should be_instance_of(WithCastedModelMixin)
end
it "should raise an error if save or update_attributes called" do
expect { @casted_obj.casted_attribute.save }.to raise_error(NoMethodError)
expect { @casted_obj.casted_attribute.update_attributes(:name => "Fubar") }.to raise_error(NoMethodError)
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
before(:each) do
@obj = DummyModel.new(:keywords => ['couch', 'sofa', 'relax', 'canapé'])
end
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'
end
end
describe "update attributes without saving" do
before(:each) do
@question = Question.new(:q => "What is your quest?", :a => "To seek the Holy Grail")
@ -218,20 +158,20 @@ describe CouchRest::Model::Embeddable do
@question['q'].should == "What is your favorite color?"
@question.a.should == "Blue"
end
it "should also work for attributes= alias" do
@question.respond_to?(:attributes=).should be_true
@question.attributes = {:q => "What is your favorite color?", 'a' => "Blue"}
@question['q'].should == "What is your favorite color?"
@question.a.should == "Blue"
end
it "should flip out if an attribute= method is missing" do
lambda {
@q.update_attributes_without_saving('foo' => "something", :a => "No green")
}.should raise_error(NoMethodError)
end
it "should not change any attributes if there is an error" do
lambda {
@q.update_attributes_without_saving('foo' => "something", :a => "No green")
@ -239,9 +179,8 @@ describe CouchRest::Model::Embeddable do
@question.q.should == "What is your quest?"
@question.a.should == "To seek the Holy Grail"
end
end
describe "saved document with casted models" do
before(:each) do
reset_test_db!
@ -249,24 +188,24 @@ describe CouchRest::Model::Embeddable do
@obj.save.should be_true
@obj = DummyModel.get(@obj.id)
end
it "should be able to load with the casted models" do
casted_obj = @obj.casted_attribute
casted_obj.should_not be_nil
casted_obj.should be_an_instance_of(WithCastedModelMixin)
end
it "should have defined getters for the casted model" do
casted_obj = @obj.casted_attribute
casted_obj.name.should == "whatever"
end
it "should have defined setters for the casted model" do
casted_obj = @obj.casted_attribute
casted_obj.name = "test"
casted_obj.name.should == "test"
end
it "should retain an override of a casted model attribute's default" do
casted_obj = @obj.casted_attribute
casted_obj.details['color'] = 'orange'
@ -274,7 +213,7 @@ describe CouchRest::Model::Embeddable do
casted_obj = DummyModel.get(@obj.id).casted_attribute
casted_obj.details['color'].should == 'orange'
end
end
describe "saving document with array of casted models and validation" do
@ -299,7 +238,7 @@ describe CouchRest::Model::Embeddable do
@cat.should_not be_valid
@cat.save.should be_false
end
it "should not fail if the casted model doesn't have validation" do
Cat.property :masters, [Person], :default => []
Cat.validates_presence_of :name
@ -309,7 +248,7 @@ describe CouchRest::Model::Embeddable do
cat.should be_valid
end
end
describe "calling valid?" do
before :each do
@cat = Cat.new
@ -320,7 +259,7 @@ describe CouchRest::Model::Embeddable do
@cat.toys << @toy2
@cat.toys << @toy3
end
describe "on the top document" do
it "should put errors on all invalid casted models" do
@cat.should_not be_valid
@ -329,23 +268,18 @@ describe CouchRest::Model::Embeddable do
@toy2.errors.should_not be_empty
@toy3.errors.should_not be_empty
end
it "should not put errors on valid casted models" do
@toy1.name = "Feather"
@toy2.name = "Twine"
@toy2.name = "Twine"
@cat.should_not be_valid
@cat.errors.should_not be_empty
@toy1.errors.should be_empty
@toy2.errors.should be_empty
@toy3.errors.should_not be_empty
end
it "should not use dperecated ActiveModel options" do
ActiveSupport::Deprecation.should_not_receive(:warn)
@cat.should_not be_valid
end
end
describe "on a casted model property" do
it "should only validate itself" do
@toy1.should_not be_valid
@ -355,7 +289,7 @@ describe CouchRest::Model::Embeddable do
@toy3.errors.should be_empty
end
end
describe "on a casted model inside a casted collection" do
it "should only validate itself" do
@toy2.should_not be_valid
@ -366,7 +300,7 @@ describe CouchRest::Model::Embeddable do
end
end
end
describe "calling new? on a casted model" do
before :each do
reset_test_db!
@ -375,18 +309,18 @@ describe CouchRest::Model::Embeddable do
@cat.favorite_toy = @favorite_toy
@cat.toys << CatToy.new(:name => 'Fuzzy Stick')
end
it "should be true on new" do
CatToy.new.should be_new
CatToy.new.new_record?.should be_true
end
it "should be true after assignment" do
@cat.should be_new
@cat.favorite_toy.should be_new
@cat.toys.first.should be_new
end
it "should not be true after create or save" do
@cat.create
@cat.save
@ -394,14 +328,14 @@ describe CouchRest::Model::Embeddable do
@cat.toys.first.casted_by.should eql(@cat)
@cat.toys.first.should_not be_new
end
it "should not be true after get from the database" do
@cat.save
@cat = Cat.get(@cat.id)
@cat.favorite_toy.should_not be_new
@cat.toys.first.should_not be_new
end
it "should still be true after a failed create or save" do
@cat.name = nil
@cat.create.should be_false
@ -410,7 +344,7 @@ describe CouchRest::Model::Embeddable do
@cat.toys.first.should be_new
end
end
describe "calling base_doc from a nested casted model" do
before :each do
@course = Course.new(:title => 'Science 101')
@ -423,15 +357,7 @@ describe CouchRest::Model::Embeddable do
@cat.favorite_toy = @toy1
@cat.toys << @toy2
end
it 'should let you copy over casted arrays' do
question = Question.new
@course.questions << question
new_course = Course.new
new_course.questions = @course.questions
new_course.questions.should include(question)
end
it "should reference the top document for" do
@course.base_doc.should === @course
@professor.casted_by.should === @course
@ -440,19 +366,19 @@ describe CouchRest::Model::Embeddable do
@toy1.base_doc.should === @course
@toy2.base_doc.should === @course
end
it "should call setter on top document" do
@toy1.base_doc.should_not be_nil
@toy1.base_doc.title = 'Tom Foolery'
@course.title.should == 'Tom Foolery'
end
it "should return nil if not yet casted" do
person = Person.new
person.base_doc.should == nil
end
end
describe "calling base_doc.save from a nested casted model" do
before :each do
reset_test_db!
@ -460,13 +386,13 @@ describe CouchRest::Model::Embeddable do
@toy = CatToy.new
@cat.favorite_toy = @toy
end
it "should not save parent document when casted model is invalid" do
@toy.should_not be_valid
@toy.base_doc.save.should be_false
lambda{@toy.base_doc.save!}.should raise_error
end
it "should save parent document when nested casted model is valid" do
@toy.name = "Mr Squeaks"
@toy.should be_valid
@ -474,25 +400,25 @@ describe CouchRest::Model::Embeddable do
lambda{@toy.base_doc.save!}.should_not raise_error
end
end
describe "callbacks" do
before(:each) do
@doc = CastedCallbackDoc.new
@model = WithCastedCallBackModel.new
@doc.callback_model = @model
end
describe "validate" do
it "should run before_validation before validating" do
@model.run_before_validation.should be_nil
it "should run before_validate before validating" do
@model.run_before_validate.should be_nil
@model.should be_valid
@model.run_before_validation.should be_true
@model.run_before_validate.should be_true
end
it "should run after_validation after validating" do
@model.run_after_validation.should be_nil
it "should run after_validate after validating" do
@model.run_after_validate.should be_nil
@model.should be_valid
@model.run_after_validation.should be_true
end
@model.run_after_validate.should be_true
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
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
# Note: no use_database here
@ -85,14 +85,8 @@ describe "Proxy Class" do
end
it "should get first" do
u = @us.first
u.should == @us.all.first
u.title.should =~ /\A...\z/
end
it "should get last" do
u = @us.last
u.should == @us.all.last
end
it "should set database on first retreived document" do
u = @us.first
u.database.should === DB
@ -123,35 +117,6 @@ describe "Proxy Class" do
u.respond_to?(:database).should be_false
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
# Removed as unclear why this should happen as before my changes
# this happend by accident, not explicitly.

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
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
@obj = WithDefaultValues.new
@ -10,17 +15,17 @@ describe CouchRest::Model::Persistence do
describe "creating a new document from database" do
it "should instantialize" do
doc = Article.build_from_database({'_id' => 'testitem1', '_rev' => 123, 'couchrest-type' => 'Article', 'name' => 'my test'})
doc = Article.create_from_database({'_id' => 'testitem1', '_rev' => 123, 'couchrest-type' => 'Article', 'name' => 'my test'})
doc.class.should eql(Article)
end
it "should instantialize of same class if no couchrest-type included from DB" do
doc = Article.build_from_database({'_id' => 'testitem1', '_rev' => 123, 'name' => 'my test'})
doc = Article.create_from_database({'_id' => 'testitem1', '_rev' => 123, 'name' => 'my test'})
doc.class.should eql(Article)
end
it "should instantialize document of different type" do
doc = Article.build_from_database({'_id' => 'testitem2', '_rev' => 123, Article.model_type_key => 'WithTemplateAndUniqueID', 'name' => 'my test'})
doc = Article.create_from_database({'_id' => 'testitem2', '_rev' => 123, 'couchrest-type' => 'WithTemplateAndUniqueID', 'name' => 'my test'})
doc.class.should eql(WithTemplateAndUniqueID)
end
@ -29,11 +34,11 @@ describe CouchRest::Model::Persistence do
describe "basic saving and retrieving" do
it "should work fine" do
@obj.name = "should be easily saved and retrieved"
@obj.save!
saved_obj = WithDefaultValues.get!(@obj.id)
@obj.save
saved_obj = WithDefaultValues.get(@obj.id)
saved_obj.should_not be_nil
end
it "should parse the Time attributes automatically" do
@obj.name = "should parse the Time attributes automatically"
@obj.set_by_proc.should be_an_instance_of(Time)
@ -76,18 +81,6 @@ describe CouchRest::Model::Persistence do
article.should_not be_new
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
doc = WithCallBacks.create(:name => 'my other test')
doc.run_before_create.should be_true
@ -121,7 +114,7 @@ describe CouchRest::Model::Persistence do
end
it "should set the type" do
@sobj[@sobj.model_type_key].should == 'Basic'
@sobj['couchrest-type'].should == 'Basic'
end
it "should accept true or false on save for validation" do
@ -217,66 +210,57 @@ describe CouchRest::Model::Persistence do
it "should require the field" do
lambda{@templated.save}.should raise_error
@templated['slug'] = 'very-important'
@templated['important-field'] = 'very-important'
@templated.save.should be_true
end
it "should save with the id" do
@templated['slug'] = 'very-important'
@templated['important-field'] = 'very-important'
@templated.save.should be_true
t = WithTemplateAndUniqueID.get('very-important')
t.should == @templated
end
it "should not change the id on update" do
@templated['slug'] = 'very-important'
@templated['important-field'] = 'very-important'
@templated.save.should be_true
@templated['slug'] = 'not-important'
@templated['important-field'] = 'not-important'
@templated.save.should be_true
t = WithTemplateAndUniqueID.get('very-important')
t.id.should == @templated.id
t.should == @templated
end
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
lambda{WithTemplateAndUniqueID.new('slug' => 'very-important').save}.should raise_error
lambda{WithTemplateAndUniqueID.new('important-field' => 'very-important').save}.should raise_error
end
it "should set the id" do
@templated['slug'] = 'very-important'
@templated['important-field'] = 'very-important'
@templated.save.should be_true
@templated.id.should == 'very-important'
end
end
describe "destroying an instance" do
before(:each) do
@dobj = Event.new
@dobj = Basic.new
@dobj.save.should be_true
end
it "should return true" do
result = @dobj.destroy
result.should be_true
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
@dobj.destroy
lambda{Basic.get!(@dobj.id)}.should raise_error(CouchRest::Model::DocumentNotFound)
end
it "should freeze the object" do
@dobj.destroy
# In Ruby 1.9.2 this raises RuntimeError, in 1.8.7 TypeError, D'OH!
lambda { @dobj.subject = "Test" }.should raise_error(StandardError)
end
it "trying to save after should fail" do
@dobj.destroy
lambda { @dobj.save }.should raise_error(StandardError)
lambda{Basic.get!(@dobj.id)}.should raise_error(CouchRest::Model::DocumentNotFound)
end
it "should make destroyed? true" do
@dobj.destroyed?.should be_false
@dobj.destroy
@dobj.destroyed?.should be_true
lambda{Basic.get!(@dobj.id)}.should raise_error
end
end
@ -298,17 +282,11 @@ describe CouchRest::Model::Persistence do
foundart = Article.get 'matt aimonetti'
foundart.should be_nil
end
it "should return nil if a blank id is requested" do
Article.get("").should be_nil
end
it "should raise an error if `get!` is used and the document doesn't exist" do
expect{ Article.get!('matt aimonetti') }.to raise_error
end
it "should raise an error if `get!` is requested with a blank id" do
expect{ Article.get!("") }.to raise_error
lambda{foundart = Article.get!('matt aimonetti')}.should raise_error
end
it "should raise an error if `find!` is used and the document doesn't exist" do
expect{ Article.find!('matt aimonetti') }.to raise_error
lambda{foundart = Article.find!('matt aimonetti')}.should raise_error
end
end
@ -345,35 +323,14 @@ describe CouchRest::Model::Persistence do
describe "validation" do
it "should run before_validation before validating" do
@doc.run_before_validation.should be_nil
@doc.run_before_validate.should be_nil
@doc.should be_valid
@doc.run_before_validation.should be_true
@doc.run_before_validate.should be_true
end
it "should run after_validation after validating" do
@doc.run_after_validation.should be_nil
@doc.run_after_validate.should be_nil
@doc.should be_valid
@doc.run_after_validation.should be_true
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
@doc.run_after_validate.should be_true
end
end
@ -449,33 +406,4 @@ describe CouchRest::Model::Persistence do
end
describe "#reload" do
it "reloads defined attributes" do
i = Article.create!(:title => "Reload when changed")
i.title.should == "Reload when changed"
i.title = "..."
i.title.should == "..."
i.reload
i.title.should == "Reload when changed"
end
it "reloads defined attributes set to nil" do
i = Article.create!(:title => "Reload when nil")
i.title.should == "Reload when nil"
i.title = nil
i.title.should be_nil
i.reload
i.title.should == "Reload when nil"
end
it "returns self" do
i = Article.create!(:title => "Reload return self")
i.reload.should be(i)
end
end
end

View file

@ -0,0 +1,804 @@
# 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 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
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 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 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
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
[ 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
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,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
Card.property :bg_color, :default => '#ccc'
@ -57,29 +61,39 @@ describe "Subclassing a Model" do
validated_fields.should_not include(:extension_code)
validated_fields.should_not include(:job_title)
end
it "should inherit default property values" do
@card.bg_color.should == '#ccc'
end
it "should be able to overwrite a default property" do
DesignBusinessCard.new.bg_color.should == '#eee'
end
it "should have a design doc slug based on the subclass name" do
Course.refresh_design_doc
OnlineCourse.design_doc_slug.should =~ /^OnlineCourse/
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
Course.design_doc['views'].keys.should_not include('by_url')
end
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')
end
it "should have an all view with a guard clause for model == subclass name in the map function" do
OnlineCourse.design_doc['views']['all']['map'].should =~ /if \(doc\['#{OnlineCourse.model_type_key}'\] == 'OnlineCourse'\)/
it "should have an all view with a guard clause for couchrest-type == subclass name in the map function" do
OnlineCourse.design_doc['views']['all']['map'].should =~ /if \(doc\['couchrest-type'\] == 'OnlineCourse'\)/
end
end

View file

@ -0,0 +1,85 @@
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 eql(['is already 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,45 +1,32 @@
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
# Note: no use_database here
property :title
property :questions
property :professor
view_by :title
# Force the database to always be nil
def self.database
nil
end
end
describe "ClassMethods" do
# NOTE! Add more unit tests!
describe "#view" do
it "should not alter original query" do
options = { :database => DB }
view = Article.view('by_date', options)
options[:database].should eql(DB)
options[:database].should_not be_nil
end
end
describe "#has_view?" do
it "should check the design doc" do
Article.design_doc.should_receive(:has_view?).with(:test).and_return(true)
Article.has_view?(:test).should be_true
end
end
describe "#can_reduce_view?" do
it "should check if view has a reduce method" do
Article.design_doc.should_receive(:can_reduce_view?).with(:test).and_return(true)
Article.can_reduce_view?(:test).should be_true
end
end
end
describe "a model with simple views and a default param" do
@ -55,6 +42,35 @@ describe CouchRest::Model::Views do
written_at += 24 * 3600
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
view = Article.by_date :raw => true
view['rows'].length.should == 4
@ -77,8 +93,9 @@ describe CouchRest::Model::Views do
Article.view_by :title
lambda{Article.by_title}.should_not raise_error
end
end
describe "another model with a simple view" do
before(:all) do
reset_test_db!
@ -167,28 +184,8 @@ describe CouchRest::Model::Views do
course.title.should eql('bbb')
end
it "should perform a search for first when reduce method present" do
course = Course.first_from_view('by_active')
course.should_not be_nil
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
before(:all) do
reset_test_db!
@ -209,7 +206,7 @@ describe CouchRest::Model::Views do
end
end
describe "a model class with database provided manually" do
describe "a model class not tied to a database" do
before(:all) do
reset_test_db!
@db = DB
@ -224,6 +221,7 @@ describe CouchRest::Model::Views do
lambda{Unattached.all}.should raise_error
end
it "should query all" do
# Unattached.cleanup_design_docs!(@db)
rs = Unattached.all :database => @db
rs.length.should == 4
end
@ -275,12 +273,18 @@ describe CouchRest::Model::Views do
u = Unattached.first :database=>@db
u.title.should =~ /\A...\z/
end
it "should get last" do
u = Unattached.last :database=>@db
u.title.should == "aaa"
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
describe "a model with a compound key view" do
@ -348,7 +352,7 @@ describe CouchRest::Model::Views do
before(:each) do
reset_test_db!
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"
end
it "should not create a design doc on view definition" do
@ -357,11 +361,103 @@ describe CouchRest::Model::Views do
newdocs["rows"].length.should == @design_docs["rows"].length
end
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.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")
end
end
describe "with a collection" do
before(:all) do
reset_test_db!
titles = ["very uniq one", "really interesting", "some fun",
"really awesome", "crazy bob", "this rocks", "super rad"]
titles.each_with_index do |title,i|
a = Article.new(:title => title, :date => Date.today)
a.save
end
titles = ["yesterday very uniq one", "yesterday really interesting", "yesterday some fun",
"yesterday really awesome", "yesterday crazy bob", "yesterday this rocks"]
titles.each_with_index do |title,i|
a = Article.new(:title => title, :date => Date.today - 1)
a.save
end
end
require 'date'
it "should return a proxy that looks like an array of 7 Article objects" do
articles = Article.by_date :key => Date.today
articles.class.should == Array
articles.size.should == 7
end
it "should get a subset of articles using paginate" do
articles = Article.by_date :key => Date.today
articles.paginate(:page => 1, :per_page => 3).size.should == 3
articles.paginate(:page => 2, :per_page => 3).size.should == 3
articles.paginate(:page => 3, :per_page => 3).size.should == 1
end
it "should get all articles, a few at a time, using paginated each" do
articles = Article.by_date :key => Date.today
articles.paginated_each(:per_page => 3) do |a|
a.should_not be_nil
end
end
it "should provide a class method to access the collection directly" do
articles = Article.collection_proxy_for('Article', 'by_date', :descending => true,
:key => Date.today, :include_docs => true)
articles.class.should == Array
articles.size.should == 7
end
it "should provide a class method for paginate" do
articles = Article.paginate(:design_doc => 'Article', :view_name => 'by_date',
:per_page => 3, :descending => true, :key => Date.today, :include_docs => true)
articles.size.should == 3
articles = Article.paginate(:design_doc => 'Article', :view_name => 'by_date',
:per_page => 3, :page => 2, :descending => true, :key => Date.today, :include_docs => true)
articles.size.should == 3
articles = Article.paginate(:design_doc => 'Article', :view_name => 'by_date',
:per_page => 3, :page => 3, :descending => true, :key => Date.today, :include_docs => true)
articles.size.should == 1
end
it "should provide a class method for paginated_each" do
options = { :design_doc => 'Article', :view_name => 'by_date',
:per_page => 3, :page => 1, :descending => true, :key => Date.today,
:include_docs => true }
Article.paginated_each(options) do |a|
a.should_not be_nil
end
end
it "should provide a class method to get a collection for a view" do
articles = Article.find_all_article_details(:key => Date.today)
articles.class.should == Array
articles.size.should == 7
end
it "should raise an exception if design_doc is not provided" do
lambda{Article.collection_proxy_for(nil, 'by_date')}.should raise_error
lambda{Article.paginate(:view_name => 'by_date')}.should raise_error
end
it "should raise an exception if view_name is not provided" do
lambda{Article.collection_proxy_for('Article', nil)}.should raise_error
lambda{Article.paginate(:design_doc => 'Article')}.should raise_error
end
it "should be able to span multiple keys" do
articles = Article.by_date :startkey => Date.today, :endkey => Date.today - 1
articles.paginate(:page => 1, :per_page => 3).size.should == 3
articles.paginate(:page => 2, :per_page => 3).size.should == 3
articles.paginate(:page => 3, :per_page => 3).size.should == 3
articles.paginate(:page => 4, :per_page => 3).size.should == 3
articles.paginate(:page => 5, :per_page => 3).size.should == 1
end
it "should pass database parameter to pager" do
proxy = mock(:proxy)
proxy.stub!(:paginate)
::CouchRest::Model::Collection::CollectionProxy.should_receive(:new).with('database', anything(), anything(), anything(), anything()).and_return(proxy)
Article.paginate(:design_doc => 'Article', :view_name => 'by_date', :database => 'database')
end
end
end

View file

@ -20,22 +20,20 @@ end
class WithCallBacks < CouchRest::Model::Base
use_database TEST_SERVER.default_database
property :name
property :run_before_validation
property :run_after_validation
property :run_before_validate
property :run_after_validate
property :run_before_save
property :run_after_save
property :run_before_create
property :run_after_create
property :run_before_update
property :run_after_update
validates_presence_of :run_before_validation
before_validation do |object|
object.run_before_validation = true
before_validate do |object|
object.run_before_validate = true
end
after_validation do |object|
object.run_after_validation = true
after_validate do |object|
object.run_after_validate = true
end
before_save do |object|
object.run_before_save = true
@ -83,32 +81,18 @@ class WithCallBacks < CouchRest::Model::Base
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
use_database TEST_SERVER.default_database
unique_id do |model|
model.slug
model['important-field']
end
property :slug
property :preset, :default => 'value'
property :has_no_default
end
class WithGetterAndSetterMethods < CouchRest::Model::Base
use_database TEST_SERVER.default_database
property :other_arg
def arg
other_arg
@ -121,7 +105,7 @@ end
class WithAfterInitializeMethod < CouchRest::Model::Base
use_database TEST_SERVER.default_database
property :some_value
def after_initialize
@ -145,20 +129,11 @@ class WithUniqueValidationView < CouchRest::Model::Base
attr_accessor :code
unique_id :code
def code
@code
self["_id"] ||= @code
end
property :title
validates_uniqueness_of :code, :view => 'all'
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

@ -9,7 +9,7 @@ class Article < CouchRest::Model::Base
view_by :tags,
:map =>
"function(doc) {
if (doc['#{model_type_key}'] == 'Article' && doc.tags) {
if (doc['couchrest-type'] == 'Article' && doc.tags) {
doc.tags.forEach(function(tag){
emit(tag, 1);
});
@ -18,11 +18,10 @@ class Article < CouchRest::Model::Base
:reduce =>
"function(keys, values, rereduce) {
return sum(values);
}"
}"
property :date, Date
property :slug, :read_only => true
property :user_id
property :title
property :tags, [String]

View file

@ -1,5 +1,3 @@
require 'person'
class Card < CouchRest::Model::Base
# Set the default database to use
use_database DB
@ -9,10 +7,10 @@ class Card < CouchRest::Model::Base
property :last_name, :alias => :family_name
property :read_only_value, :read_only => true
property :cast_alias, Person, :alias => :calias
property :fg_color, :default => '#000'
timestamps!
# Validation
validates_presence_of :first_name

View file

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

View file

@ -1,5 +1,5 @@
require 'question'
require 'person'
require File.join(FIXTURE_PATH, 'more', 'question')
require File.join(FIXTURE_PATH, 'more', 'person')
class Course < CouchRest::Model::Base
use_database TEST_SERVER.default_database
@ -13,15 +13,13 @@ class Course < CouchRest::Model::Base
property :hours, Integer
property :profit, BigDecimal
property :started_on, :type => Date
property :updated_at, DateTime
property :updated_at, :type => DateTime
property :active, :type => TrueClass
property :very_active, :type => TrueClass
property :klass, :type => Class
view_by :title
view_by :title, :active
view_by :dept, :ducktype => true
view_by :active, :map => "function(d) { if (d['#{model_type_key}'] == 'Course' && d['active']) { emit(d['updated_at'], 1); }}", :reduce => "function(k,v,r) { return sum(v); }"
end

View file

@ -6,9 +6,9 @@ class Invoice < CouchRest::Model::Base
property :client_name
property :employee_name
property :location
# Validation
validates_presence_of :client_name, :employee_name
validates_presence_of :location, :message => "Hey stupid!, you forgot the location"
end

View file

@ -1,7 +1,5 @@
require 'cat'
class Person
include ::CouchRest::Model::Embeddable
class Person < Hash
include ::CouchRest::Model::CastedModel
property :pet, Cat
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,7 +1,6 @@
require 'client'
require 'sale_entry'
class SaleInvoice < CouchRest::Model::Base
require File.join(FIXTURE_PATH, 'more', 'client')
require File.join(FIXTURE_PATH, 'more', 'sale_entry')
class SaleInvoice < CouchRest::Model::Base
use_database DB
belongs_to :client
@ -11,4 +10,4 @@ class SaleInvoice < CouchRest::Model::Base
property :date, Date
property :price, Integer
end
end

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,4 +1,5 @@
--colour
--format
progress
--loadby
mtime

View file

@ -1,29 +1,32 @@
$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "lib"))
require "bundler/setup"
require "rubygems"
require "rspec"
require "spec" # 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)
MODEL_PATH = File.join(File.dirname(__FILE__), "fixtures", "models")
$LOAD_PATH.unshift(MODEL_PATH)
FIXTURE_PATH = File.join(File.dirname(__FILE__), '/fixtures')
SCRATCH_PATH = File.join(File.dirname(__FILE__), '/tmp')
COUCHHOST = "http://127.0.0.1:5984"
TESTDB = 'couchrest-model-test'
TEST_SERVER = CouchRest.new COUCHHOST
TEST_SERVER = CouchRest.new
TEST_SERVER.default_database = TESTDB
DB = TEST_SERVER.database(TESTDB)
end
RSpec.configure do |config|
config.before(:all) { reset_test_db! }
class Basic < CouchRest::Model::Base
use_database TEST_SERVER.default_database
end
def reset_test_db!
DB.recreate! rescue nil
DB
end
Spec::Runner.configure do |config|
config.before(:all) { reset_test_db! }
config.after(:all) do
cr = TEST_SERVER
test_dbs = cr.databases.select { |db| db =~ /^#{TESTDB}/ }
@ -33,21 +36,6 @@ RSpec.configure do |config|
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?
lucene_path = "http://localhost:5985/"
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,86 +0,0 @@
require "spec_helper"
describe "Collections" do
before(:all) do
reset_test_db!
titles = ["very uniq one", "really interesting", "some fun",
"really awesome", "crazy bob", "this rocks", "super rad"]
titles.each_with_index do |title,i|
a = Article.new(:title => title, :date => Date.today)
a.save
end
titles = ["yesterday very uniq one", "yesterday really interesting", "yesterday some fun",
"yesterday really awesome", "yesterday crazy bob", "yesterday this rocks"]
titles.each_with_index do |title,i|
a = Article.new(:title => title, :date => Date.today - 1)
a.save
end
end
it "should return a proxy that looks like an array of 7 Article objects" do
articles = Article.collection_proxy_for('Article', 'by_date', :descending => true,
:key => Date.today, :include_docs => true)
articles.class.should == Array
articles.size.should == 7
end
it "should provide a class method for paginate" do
articles = Article.paginate(:design_doc => 'Article', :view_name => 'by_date',
:per_page => 3, :descending => true, :key => Date.today)
articles.size.should == 3
articles = Article.paginate(:design_doc => 'Article', :view_name => 'by_date',
:per_page => 3, :page => 2, :descending => true, :key => Date.today)
articles.size.should == 3
articles = Article.paginate(:design_doc => 'Article', :view_name => 'by_date',
:per_page => 3, :page => 3, :descending => true, :key => Date.today)
articles.size.should == 1
end
it "should provide a class method for paginated_each" do
options = { :design_doc => 'Article', :view_name => 'by_date',
:per_page => 3, :page => 1, :descending => true, :key => Date.today }
Article.paginated_each(options) do |a|
a.should_not be_nil
end
end
it "should provide a class method to get a collection for a view" do
articles = Article.find_all_article_details(:key => Date.today)
articles.class.should == Array
articles.size.should == 7
end
it "should get a subset of articles using paginate" do
articles = Article.collection_proxy_for('Article', 'by_date', :key => Date.today, :include_docs => true)
articles.paginate(:page => 1, :per_page => 3).size.should == 3
articles.paginate(:page => 2, :per_page => 3).size.should == 3
articles.paginate(:page => 3, :per_page => 3).size.should == 1
end
it "should get all articles, a few at a time, using paginated each" do
articles = Article.collection_proxy_for('Article', 'by_date', :key => Date.today, :include_docs => true)
articles.paginated_each(:per_page => 3) do |a|
a.should_not be_nil
end
end
it "should raise an exception if design_doc is not provided" do
lambda{Article.collection_proxy_for(nil, 'by_date')}.should raise_error
lambda{Article.paginate(:view_name => 'by_date')}.should raise_error
end
it "should raise an exception if view_name is not provided" do
lambda{Article.collection_proxy_for('Article', nil)}.should raise_error
lambda{Article.paginate(:design_doc => 'Article')}.should raise_error
end
it "should be able to span multiple keys" do
articles = Article.collection_proxy_for('Article', 'by_date', :startkey => Date.today - 1, :endkey => Date.today, :include_docs => true)
articles.paginate(:page => 1, :per_page => 3).size.should == 3
articles.paginate(:page => 3, :per_page => 3).size.should == 3
articles.paginate(:page => 5, :per_page => 3).size.should == 1
end
it "should pass database parameter to pager" do
proxy = mock(:proxy)
proxy.stub!(:paginate)
::CouchRest::Model::Collection::CollectionProxy.should_receive(:new).with('database', anything(), anything(), anything(), anything()).and_return(proxy)
Article.paginate(:design_doc => 'Article', :view_name => 'by_date', :database => 'database')
end
end

View file

@ -1,77 +0,0 @@
# encoding: utf-8
require "spec_helper"
describe CouchRest::Model::Configuration do
before do
@class = Class.new(CouchRest::Model::Base)
end
describe '.configure' do
it "should set a configuration parameter" do
@class.add_config :foo_bar
@class.configure do |config|
config.foo_bar = 'monkey'
end
@class.foo_bar.should == 'monkey'
end
end
describe '.add_config' do
it "should add a class level accessor" do
@class.add_config :foo_bar
@class.foo_bar = 'foo'
@class.foo_bar.should == 'foo'
end
['foo', :foo, 45, ['foo', :bar]].each do |val|
it "should be inheritable for a #{val.class}" do
@class.add_config :foo_bar
@child_class = Class.new(@class)
@class.foo_bar = val
@class.foo_bar.should == val
@child_class.foo_bar.should == val
@child_class.foo_bar = "bar"
@child_class.foo_bar.should == "bar"
@class.foo_bar.should == val
end
end
it "should add an instance level accessor" do
@class.add_config :foo_bar
@class.foo_bar = 'foo'
@class.new.foo_bar.should == 'foo'
end
it "should add a convenient in-class setter" do
@class.add_config :foo_bar
@class.foo_bar "monkey"
@class.foo_bar.should == "monkey"
end
end
describe "General examples" do
before(:all) do
@default_model_key = 'model-type'
end
it "should be possible to override on class using configure method" do
default_model_key = Cat.model_type_key
Cat.instance_eval do
model_type_key 'cat-type'
end
CouchRest::Model::Base.model_type_key.should eql(default_model_key)
Cat.model_type_key.should eql('cat-type')
cat = Cat.new
cat.model_type_key.should eql('cat-type')
end
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,831 +0,0 @@
require File.expand_path("../../../spec_helper", __FILE__)
class DesignViewModel < CouchRest::Model::Base
use_database DB
property :name
property :title
design do
view :by_name
view :by_just_name, :map => "function(doc) { emit(doc['name'], null); }"
end
end
describe "Design View" do
describe "(unit tests)" do
before :each do
@klass = CouchRest::Model::Designs::View
end
describe ".new" do
describe "with invalid parent model" do
it "should burn" do
lambda { @klass.new(String) }.should raise_exception
end
end
describe "with CouchRest Model" do
it "should setup attributes" do
@obj = @klass.new(DesignViewModel, {}, 'test_view')
@obj.model.should eql(DesignViewModel)
@obj.name.should eql('test_view')
@obj.query.should be_empty
end
it "should complain if there is no name" do
lambda { @klass.new(DesignViewModel, {}, nil) }.should raise_error
end
end
describe "with previous view instance" do
before :each do
first = @klass.new(DesignViewModel, {}, 'test_view')
@obj = @klass.new(first, {:foo => :bar})
end
it "should copy attributes" do
@obj.model.should eql(DesignViewModel)
@obj.name.should eql('test_view')
@obj.query.should eql({:foo => :bar})
end
end
end
describe ".create" do
before :each do
@design_doc = {}
DesignViewModel.stub!(:design_doc).and_return(@design_doc)
end
it "should add a basic view" do
@klass.create(DesignViewModel, 'test_view', :map => 'foo')
@design_doc['views']['test_view'].should_not be_nil
end
it "should auto generate mapping from name" do
lambda { @klass.create(DesignViewModel, 'by_title') }.should_not raise_error
str = @design_doc['views']['by_title']['map']
str.should include("((doc['#{DesignViewModel.model_type_key}'] == 'DesignViewModel') && (doc['title'] != null))")
str.should include("emit(doc['title'], 1);")
str = @design_doc['views']['by_title']['reduce']
str.should include("return sum(values);")
end
it "should auto generate mapping from name with and" do
@klass.create(DesignViewModel, 'by_title_and_name')
str = @design_doc['views']['by_title_and_name']['map']
str.should include("(doc['title'] != null) && (doc['name'] != null)")
str.should include("emit([doc['title'], doc['name']], 1);")
str = @design_doc['views']['by_title_and_name']['reduce']
str.should include("return sum(values);")
end
end
describe "instance methods" do
before :each do
@obj = @klass.new(DesignViewModel, {}, 'test_view')
end
describe "#rows" do
it "should execute query" do
@obj.should_receive(:execute).and_return(true)
@obj.should_receive(:result).twice.and_return({'rows' => []})
@obj.rows.should be_empty
end
it "should wrap rows in ViewRow class" do
@obj.should_receive(:execute).and_return(true)
@obj.should_receive(:result).twice.and_return({'rows' => [{:foo => :bar}]})
CouchRest::Model::Designs::ViewRow.should_receive(:new).with({:foo => :bar}, @obj.model)
@obj.rows
end
end
describe "#all" do
it "should ensure docs included and call docs" do
@obj.should_receive(:include_docs!)
@obj.should_receive(:docs)
@obj.all
end
end
describe "#docs" do
it "should provide docs from rows" do
@obj.should_receive(:rows).and_return([])
@obj.docs
end
it "should cache the results" do
@obj.should_receive(:rows).once.and_return([])
@obj.docs
@obj.docs
end
end
describe "#first" do
it "should provide the first result of loaded query" do
@obj.should_receive(:result).and_return(true)
@obj.should_receive(:all).and_return([:foo])
@obj.first.should eql(:foo)
end
it "should perform a query if no results cached" do
view = mock('SubView')
@obj.should_receive(:result).and_return(nil)
@obj.should_receive(:limit).with(1).and_return(view)
view.should_receive(:all).and_return([:foo])
@obj.first.should eql(:foo)
end
end
describe "#last" do
it "should provide the last result of loaded query" do
@obj.should_receive(:result).and_return(true)
@obj.should_receive(:all).and_return([:foo, :bar])
@obj.first.should eql(:foo)
end
it "should perform a query if no results cached" do
view = mock('SubView')
@obj.should_receive(:result).and_return(nil)
@obj.should_receive(:limit).with(1).and_return(view)
view.should_receive(:descending).and_return(view)
view.should_receive(:all).and_return([:foo, :bar])
@obj.last.should eql(:bar)
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
it "should raise an error if view prepared for group" do
@obj.should_receive(:query).and_return({:group => true})
lambda { @obj.count }.should raise_error(/group/)
end
it "should return first row value if reduce possible" do
view = mock("SubView")
row = mock("Row")
@obj.should_receive(:can_reduce?).and_return(true)
@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])
row.should_receive(:value).and_return(2)
@obj.count.should eql(2)
end
it "should return 0 if no rows and reduce possible" do
view = mock("SubView")
@obj.should_receive(:can_reduce?).and_return(true)
@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([])
@obj.count.should eql(0)
end
it "should perform limit request for total_rows" do
view = mock("SubView")
@obj.should_receive(:limit).with(0).and_return(view)
view.should_receive(:total_rows).and_return(4)
@obj.should_receive(:can_reduce?).and_return(false)
@obj.count.should eql(4)
end
end
describe "#empty?" do
it "should check the #all method for any results" do
all = mock("All")
all.should_receive(:empty?).and_return('win')
@obj.should_receive(:all).and_return(all)
@obj.empty?.should eql('win')
end
end
describe "#each" do
it "should call each method on all" do
@obj.should_receive(:all).and_return([])
@obj.each
end
it "should call each and pass block" do
set = [:foo, :bar]
@obj.should_receive(:all).and_return(set)
result = []
@obj.each do |s|
result << s
end
result.should eql(set)
end
end
describe "#offset" do
it "should excute" do
@obj.should_receive(:execute).and_return({'offset' => 3})
@obj.offset.should eql(3)
end
end
describe "#total_rows" do
it "should excute" do
@obj.should_receive(:execute).and_return({'total_rows' => 3})
@obj.total_rows.should eql(3)
end
end
describe "#values" do
it "should request each row and provide value" do
row = mock("Row")
row.should_receive(:value).twice.and_return('foo')
@obj.should_receive(:rows).and_return([row, row])
@obj.values.should eql(['foo', 'foo'])
end
end
describe "#[]" do
it "should execute and provide requested field" do
@obj.should_receive(:execute).and_return({'total_rows' => 2})
@obj['total_rows'].should eql(2)
end
end
describe "#info" do
it "should raise error" do
lambda { @obj.info }.should raise_error
end
end
describe "#database" do
it "should update query with value" do
@obj.should_receive(:update_query).with({:database => 'foo'})
@obj.database('foo')
end
end
describe "#key" do
it "should update query with value" do
@obj.should_receive(:update_query).with({:key => 'foo'})
@obj.key('foo')
end
it "should raise error if startkey set" do
@obj.query[:startkey] = 'bar'
lambda { @obj.key('foo') }.should raise_error
end
it "should raise error if endkey set" do
@obj.query[:endkey] = 'bar'
lambda { @obj.key('foo') }.should raise_error
end
it "should raise error if both startkey and endkey set" do
@obj.query[:startkey] = 'bar'
@obj.query[:endkey] = 'bar'
lambda { @obj.key('foo') }.should raise_error
end
it "should raise error if keys set" do
@obj.query[:keys] = 'bar'
lambda { @obj.key('foo') }.should raise_error
end
end
describe "#startkey" do
it "should update query with value" do
@obj.should_receive(:update_query).with({:startkey => 'foo'})
@obj.startkey('foo')
end
it "should raise and error if key set" do
@obj.query[:key] = 'bar'
lambda { @obj.startkey('foo') }.should raise_error(/View#startkey/)
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
describe "#startkey_doc" do
it "should update query with value" do
@obj.should_receive(:update_query).with({:startkey_docid => 'foo'})
@obj.startkey_doc('foo')
end
it "should update query with object id if available" do
doc = mock("Document")
doc.should_receive(:id).and_return(44)
@obj.should_receive(:update_query).with({:startkey_docid => 44})
@obj.startkey_doc(doc)
end
end
describe "#endkey" do
it "should update query with value" do
@obj.should_receive(:update_query).with({:endkey => 'foo'})
@obj.endkey('foo')
end
it "should raise and error if key set" do
@obj.query[:key] = 'bar'
lambda { @obj.endkey('foo') }.should raise_error(/View#endkey/)
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
describe "#endkey_doc" do
it "should update query with value" do
@obj.should_receive(:update_query).with({:endkey_docid => 'foo'})
@obj.endkey_doc('foo')
end
it "should update query with object id if available" do
doc = mock("Document")
doc.should_receive(:id).and_return(44)
@obj.should_receive(:update_query).with({:endkey_docid => 44})
@obj.endkey_doc(doc)
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
it "should update query" do
@obj.should_receive(:update_query).with({:descending => true})
@obj.descending
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
describe "#limit" do
it "should update query with value" do
@obj.should_receive(:update_query).with({:limit => 3})
@obj.limit(3)
end
end
describe "#skip" do
it "should update query with value" do
@obj.should_receive(:update_query).with({:skip => 3})
@obj.skip(3)
end
it "should update query with default value" do
@obj.should_receive(:update_query).with({:skip => 0})
@obj.skip
end
end
describe "#reduce" do
it "should update query" do
@obj.should_receive(:can_reduce?).and_return(true)
@obj.should_receive(:update_query).with({:reduce => true, :include_docs => nil})
@obj.reduce
end
it "should raise error if query cannot be reduced" do
@obj.should_receive(:can_reduce?).and_return(false)
lambda { @obj.reduce }.should raise_error
end
end
describe "#group" do
it "should update query" do
@obj.should_receive(:query).and_return({:reduce => true})
@obj.should_receive(:update_query).with({:group => true})
@obj.group
end
it "should raise error if query not prepared for reduce" do
@obj.should_receive(:query).and_return({:reduce => false})
lambda { @obj.group }.should raise_error
end
end
describe "#group" do
it "should update query" do
@obj.should_receive(:query).and_return({:reduce => true})
@obj.should_receive(:update_query).with({:group => true})
@obj.group
end
it "should raise error if query not prepared for reduce" do
@obj.should_receive(:query).and_return({:reduce => false})
lambda { @obj.group }.should raise_error
end
end
describe "#group_level" do
it "should update query" do
@obj.should_receive(:group).and_return(@obj)
@obj.should_receive(:update_query).with({:group_level => 3})
@obj.group_level(3)
end
end
describe "#include_docs" do
it "should call include_docs! on new view" do
@obj.should_receive(:update_query).and_return(@obj)
@obj.should_receive(:include_docs!)
@obj.include_docs
end
end
describe "#reset!" do
it "should empty all cached data" do
@obj.should_receive(:result=).with(nil)
@obj.instance_exec { @rows = 'foo'; @docs = 'foo' }
@obj.reset!
@obj.instance_exec { @rows }.should be_nil
@obj.instance_exec { @docs }.should be_nil
end
end
#### PROTECTED METHODS
describe "#include_docs!" do
it "should set query value" do
@obj.should_receive(:result).and_return(false)
@obj.should_not_receive(:reset!)
@obj.send(:include_docs!)
@obj.query[:include_docs].should be_true
end
it "should reset if result and no docs" do
@obj.should_receive(:result).and_return(true)
@obj.should_receive(:include_docs?).and_return(false)
@obj.should_receive(:reset!)
@obj.send(:include_docs!)
@obj.query[:include_docs].should be_true
end
it "should raise an error if view is reduced" do
@obj.query[:reduce] = true
lambda { @obj.send(:include_docs!) }.should raise_error
end
end
describe "#include_docs?" do
it "should return true if set" do
@obj.should_receive(:query).and_return({:include_docs => true})
@obj.send(:include_docs?).should be_true
end
it "should return false if not set" do
@obj.should_receive(:query).and_return({})
@obj.send(:include_docs?).should be_false
@obj.should_receive(:query).and_return({:include_docs => false})
@obj.send(:include_docs?).should be_false
end
end
describe "#update_query" do
it "returns a new instance of view" do
@obj.send(:update_query).object_id.should_not eql(@obj.object_id)
end
it "returns a new instance of view with extra parameters" do
new_obj = @obj.send(:update_query, {:foo => :bar})
new_obj.query[:foo].should eql(:bar)
end
end
describe "#design_doc" do
it "should call design_doc on model" do
@obj.model.should_receive(:design_doc)
@obj.send(:design_doc)
end
end
describe "#can_reduce?" do
it "should check and prove true" do
@obj.should_receive(:name).and_return('test_view')
@obj.should_receive(:design_doc).and_return({'views' => {'test_view' => {'reduce' => 'foo'}}})
@obj.send(:can_reduce?).should be_true
end
it "should check and prove false" do
@obj.should_receive(:name).and_return('test_view')
@obj.should_receive(:design_doc).and_return({'views' => {'test_view' => {'reduce' => nil}}})
@obj.send(:can_reduce?).should be_false
end
end
describe "#execute" do
before :each do
# disable real execution!
@design_doc = mock("DesignDoc")
@design_doc.stub!(:view_on)
@obj.model.stub!(:save_design_doc)
@obj.model.stub!(:design_doc).and_return(@design_doc)
end
it "should return previous result if set" do
@obj.result = "foo"
@obj.send(:execute).should eql('foo')
end
it "should raise issue if no database" do
@obj.should_receive(:query).and_return({:database => nil})
model = mock("SomeModel")
model.should_receive(:database).and_return(nil)
@obj.should_receive(:model).and_return(model)
lambda { @obj.send(:execute) }.should raise_error
end
it "should delete the reduce option if not going to be used" do
@obj.should_receive(:can_reduce?).and_return(false)
@obj.query.should_receive(:delete).with(:reduce)
@obj.send(:execute)
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
@obj.should_receive(:can_reduce?).and_return(true)
@design_doc.should_receive(:view_on).and_return('foos')
@obj.send(:execute)
@obj.result.should eql('foos')
end
it "should remove nil values from query" do
@obj.should_receive(:can_reduce?).and_return(true)
@obj.stub!(:use_database).and_return('database')
@obj.query = {:reduce => true, :limit => nil, :skip => nil}
@design_doc.should_receive(:view_on).with('database', 'test_view', {:reduce => true})
@obj.send(:execute)
end
end
describe "pagination methods" do
describe "#page" do
it "should call limit and skip" do
@obj.should_receive(:limit).with(25).and_return(@obj)
@obj.should_receive(:skip).with(25).and_return(@obj)
@obj.page(2)
end
end
describe "#per" do
it "should raise an error if page not called before hand" do
lambda { @obj.per(12) }.should raise_error
end
it "should not do anything if number less than or eql 0" do
view = @obj.page(1)
view.per(0).should eql(view)
end
it "should set limit and update skip" do
view = @obj.page(2).per(10)
view.query[:skip].should eql(10)
view.query[:limit].should eql(10)
end
end
describe "#total_count" do
it "set limit and skip to nill and perform count" do
@obj.should_receive(:limit).with(nil).and_return(@obj)
@obj.should_receive(:skip).with(nil).and_return(@obj)
@obj.should_receive(:count).and_return(5)
@obj.total_count.should eql(5)
@obj.total_count.should eql(5) # Second to test caching
end
end
describe "#num_pages" do
it "should use total_count and limit_value" do
@obj.should_receive(:total_count).and_return(200)
@obj.should_receive(:limit_value).and_return(25)
@obj.num_pages.should eql(8)
end
end
describe "#current_page" do
it "should use offset and limit" do
@obj.should_receive(:offset_value).and_return(25)
@obj.should_receive(:limit_value).and_return(25)
@obj.current_page.should eql(2)
end
end
end
end
end
describe "ViewRow" do
before :all do
@klass = CouchRest::Model::Designs::ViewRow
end
describe "intialize" do
it "should store reference to model" do
obj = @klass.new({}, "model")
obj.model.should eql('model')
end
it "should copy details from hash" do
obj = @klass.new({:foo => :bar, :test => :example}, "")
obj[:foo].should eql(:bar)
obj[:test].should eql(:example)
end
end
describe "running" do
before :each do
end
it "should provide id" do
obj = @klass.new({'id' => '123456'}, 'model')
obj.id.should eql('123456')
end
it "should provide key" do
obj = @klass.new({'key' => 'thekey'}, 'model')
obj.key.should eql('thekey')
end
it "should provide the value" do
obj = @klass.new({'value' => 'thevalue'}, 'model')
obj.value.should eql('thevalue')
end
it "should provide the raw document" do
obj = @klass.new({'doc' => 'thedoc'}, 'model')
obj.raw_doc.should eql('thedoc')
end
it "should instantiate a new document" do
hash = {'doc' => {'_id' => '12345', 'name' => 'sam'}}
obj = @klass.new(hash, DesignViewModel)
doc = mock('DesignViewModel')
obj.model.should_receive(:build_from_database).with(hash['doc']).and_return(doc)
obj.doc.should eql(doc)
end
it "should try to load from id if no document" do
hash = {'id' => '12345', 'value' => 5}
obj = @klass.new(hash, DesignViewModel)
doc = mock('DesignViewModel')
obj.model.should_receive(:get).with('12345').and_return(doc)
obj.doc.should eql(doc)
end
it "should try to load linked document if available" do
hash = {'id' => '12345', 'value' => {'_id' => '54321'}}
obj = @klass.new(hash, DesignViewModel)
doc = mock('DesignViewModel')
obj.model.should_receive(:get).with('54321').and_return(doc)
obj.doc.should eql(doc)
end
it "should try to return nil for document if none available" do
hash = {'value' => 23} # simulate reduce
obj = @klass.new(hash, DesignViewModel)
doc = mock('DesignViewModel')
obj.model.should_not_receive(:get)
obj.doc.should be_nil
end
end
end
describe "scenarios" do
before :all do
@objs = [
{:name => "Judith"},
{:name => "Lorena"},
{:name => "Peter"},
{:name => "Sam"},
{:name => "Vilma"}
].map{|h| DesignViewModel.create(h)}
end
describe "loading documents" do
it "should return first" do
DesignViewModel.by_name.first.name.should eql("Judith")
end
it "should return last" do
DesignViewModel.by_name.last.name.should eql("Vilma")
end
it "should allow multiple results" do
view = DesignViewModel.by_name.limit(3)
view.total_rows.should eql(5)
view.last.name.should eql("Peter")
view.all.length.should eql(3)
end
end
describe "index information" do
it "should provide total_rows" do
DesignViewModel.by_name.total_rows.should eql(5)
end
it "should provide total_rows" do
DesignViewModel.by_name.total_rows.should eql(5)
end
it "should provide an offset" do
DesignViewModel.by_name.offset.should eql(0)
end
it "should provide a set of keys" do
DesignViewModel.by_name.limit(2).keys.should eql(["Judith", "Lorena"])
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
before :all do
DesignViewModel.paginates_per 3
end
before :each do
@view = DesignViewModel.by_name.page(1)
end
it "should calculate number of pages" do
@view.num_pages.should eql(2)
end
it "should return results from first page" do
@view.all.first.name.should eql('Judith')
@view.all.last.name.should eql('Peter')
end
it "should return results from second page" do
@view.page(2).all.first.name.should eql('Sam')
@view.page(2).all.last.name.should eql('Vilma')
end
it "should allow overriding per page count" do
@view = @view.per(10)
@view.num_pages.should eql(1)
@view.all.last.name.should eql('Vilma')
end
end
end
end

View file

@ -1,134 +0,0 @@
require "spec_helper"
class DesignModel < CouchRest::Model::Base
end
describe CouchRest::Model::Designs do
it "should accessable from model" do
DesignModel.respond_to?(:design).should be_true
end
describe "class methods" do
describe ".design" do
before :each do
@mapper = mock('DesignMapper')
@mapper.stub!(:create_view_method)
end
it "should instantiate a new DesignMapper" do
CouchRest::Model::Designs::DesignMapper.should_receive(:new).with(DesignModel).and_return(@mapper)
@mapper.should_receive(:create_view_method).with(:all)
@mapper.should_receive(:instance_eval)
DesignModel.design() { }
end
it "should allow methods to be called in mapper" do
@mapper.should_receive(:foo)
CouchRest::Model::Designs::DesignMapper.stub!(:new).and_return(@mapper)
DesignModel.design { foo }
end
it "should work even if a block is not provided" do
lambda { DesignModel.design }.should_not raise_error
end
end
describe "default_per_page" do
it "should return 25 default" do
DesignModel.default_per_page.should eql(25)
end
end
describe ".paginates_per" do
it "should set the default per page value" do
DesignModel.paginates_per(21)
DesignModel.default_per_page.should eql(21)
end
end
end
describe "DesignMapper" do
before :all do
@klass = CouchRest::Model::Designs::DesignMapper
end
it "should initialize and set model" do
object = @klass.new(DesignModel)
object.send(:model).should eql(DesignModel)
end
describe "#view" do
before :each do
@object = @klass.new(DesignModel)
end
it "should call create method on view" do
CouchRest::Model::Designs::View.should_receive(:create).with(DesignModel, 'test', {})
@object.view('test')
end
it "should create a method on parent model" do
CouchRest::Model::Designs::View.stub!(:create)
@object.view('test_view')
DesignModel.should respond_to(:test_view)
end
it "should create a method for view instance" do
CouchRest::Model::Designs::View.stub!(:create)
@object.should_receive(:create_view_method).with('test')
@object.view('test')
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
describe "#create_view_method" do
before :each do
@object = @klass.new(DesignModel)
end
it "should create a method that returns view instance" do
CouchRest::Model::Designs::View.should_receive(:new).with(DesignModel, {}, 'test_view').and_return(nil)
@object.create_view_method('test_view')
DesignModel.test_view
end
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,376 +0,0 @@
require "spec_helper"
class DummyProxyable < CouchRest::Model::Base
proxy_database_method :db
def db
'db'
end
end
class ProxyKitten < CouchRest::Model::Base
end
describe CouchRest::Model::Proxyable do
describe "#proxy_database" do
before do
@class = Class.new(CouchRest::Model::Base)
@class.class_eval do
def slug; 'proxy'; end
end
@obj = @class.new
end
it "should respond to method" do
@obj.should respond_to(:proxy_database)
end
it "should provide proxy database from method" do
@class.stub!(:proxy_database_method).twice.and_return(:slug)
@obj.proxy_database.should be_a(CouchRest::Database)
@obj.proxy_database.name.should eql('couchrest_proxy')
end
it "should raise an error if called and no proxy_database_method set" do
lambda { @obj.proxy_database }.should raise_error(StandardError, /Please set/)
end
end
describe "class methods" do
describe ".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
before(:each) do
@class = DummyProxyable.clone
end
it "should be provided" do
@class.should respond_to(:proxy_for)
end
it "should create a new method" do
DummyProxyable.stub!(:method_defined?).and_return(true)
DummyProxyable.proxy_for(:cats)
DummyProxyable.new.should respond_to(:cats)
end
describe "generated method" do
it "should call ModelProxy" do
DummyProxyable.proxy_for(:cats)
@obj = DummyProxyable.new
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.cats
end
it "should call class on root namespace" do
class ::Document < CouchRest::Model::Base
def self.foo; puts 'bar'; end
end
DummyProxyable.proxy_for(:documents)
@obj = DummyProxyable.new
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.documents
end
end
end
describe ".proxied_by" do
before do
@class = Class.new(CouchRest::Model::Base)
end
it "should be provided" do
@class.should respond_to(:proxied_by)
end
it "should add an attribute accessor" do
@class.proxied_by(:foobar)
@class.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
it "should raise an error if model name pre-defined" do
lambda { @class.proxied_by(:object_id) }.should raise_error
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
describe "ModelProxy" do
before :all do
@klass = CouchRest::Model::Proxyable::ModelProxy
end
it "should initialize and set variables" do
@obj = @klass.new(Cat, 'owner', 'owner_name', 'database')
@obj.model.should eql(Cat)
@obj.owner.should eql('owner')
@obj.owner_name.should eql('owner_name')
@obj.database.should eql('database')
end
describe "instance" do
before :each do
@obj = @klass.new(Cat, 'owner', 'owner_name', 'database')
end
it "should proxy new call" do
@obj.should_receive(:proxy_block_update).with(:new, 'attrs', 'opts')
@obj.new('attrs', 'opts')
end
it "should proxy build_from_database" do
@obj.should_receive(:proxy_block_update).with(:build_from_database, 'attrs', 'opts')
@obj.build_from_database('attrs', 'opts')
end
describe "#method_missing" do
it "should return design view object" do
m = "by_some_property"
inst = mock('DesignView')
inst.stub!(:proxy).and_return(inst)
@obj.should_receive(:has_view?).with(m).and_return(true)
Cat.should_receive(:respond_to?).with(m).and_return(true)
Cat.should_receive(:send).with(m).and_return(inst)
@obj.method_missing(m).should eql(inst)
end
it "should call view if necessary" do
m = "by_some_property"
@obj.should_receive(:has_view?).with(m).and_return(true)
Cat.should_receive(:respond_to?).with(m).and_return(false)
@obj.should_receive(:view).with(m, {}).and_return('view')
@obj.method_missing(m).should eql('view')
end
it "should provide wrapper for #first_from_view" do
m = "find_by_some_property"
view = "by_some_property"
@obj.should_receive(:has_view?).with(m).and_return(false)
@obj.should_receive(:has_view?).with(view).and_return(true)
@obj.should_receive(:first_from_view).with(view).and_return('view')
@obj.method_missing(m).should eql('view')
end
end
it "should proxy #all" do
Cat.should_receive(:all).with({:database => 'database'})
@obj.should_receive(:proxy_update_all)
@obj.all
end
it "should proxy #count" do
Cat.should_receive(:all).with({:database => 'database', :raw => true, :limit => 0}).and_return({'total_rows' => 3})
@obj.count.should eql(3)
end
it "should proxy #first" do
Cat.should_receive(:first).with({:database => 'database'})
@obj.should_receive(:proxy_update)
@obj.first
end
it "should proxy #last" do
Cat.should_receive(:last).with({:database => 'database'})
@obj.should_receive(:proxy_update)
@obj.last
end
it "should proxy #get" do
Cat.should_receive(:get).with(32, 'database')
@obj.should_receive(:proxy_update)
@obj.get(32)
end
it "should proxy #find" do
Cat.should_receive(:get).with(32, 'database')
@obj.should_receive(:proxy_update)
@obj.find(32)
end
it "should proxy #has_view?" do
Cat.should_receive(:has_view?).with('view').and_return(false)
@obj.has_view?('view')
end
it "should proxy #view_by" do
Cat.should_receive(:view_by).with('name').and_return(false)
@obj.view_by('name')
end
it "should proxy #view" do
Cat.should_receive(:view).with('view', {:database => 'database'})
@obj.should_receive(:proxy_update_all)
@obj.view('view')
end
it "should proxy #first_from_view" do
Cat.should_receive(:first_from_view).with('view', {:database => 'database'})
@obj.should_receive(:proxy_update)
@obj.first_from_view('view')
end
it "should proxy design_doc" do
Cat.should_receive(:design_doc)
@obj.design_doc
end
describe "#save_design_doc" do
it "should be proxied without args" do
Cat.should_receive(:save_design_doc).with('database')
@obj.save_design_doc
end
it "should be proxied with database arg" do
Cat.should_receive(:save_design_doc).with('db')
@obj.save_design_doc('db')
end
end
### Updating methods
describe "#proxy_update" do
it "should set returned doc fields" do
doc = mock(:Document)
doc.should_receive(:is_a?).with(Cat).and_return(true)
doc.should_receive(:database=).with('database')
doc.should_receive(:model_proxy=).with(@obj)
doc.should_receive(:send).with('owner_name=', 'owner')
@obj.send(:proxy_update, doc).should eql(doc)
end
it "should not set anything if matching document not provided" do
doc = mock(:DocumentFoo)
doc.should_receive(:is_a?).with(Cat).and_return(false)
doc.should_not_receive(:database=)
doc.should_not_receive(:model_proxy=)
doc.should_not_receive(:owner_name=)
@obj.send(:proxy_update, doc).should eql(doc)
end
it "should pass nil straight through without errors" do
lambda { @obj.send(:proxy_update, nil).should eql(nil) }.should_not raise_error
end
end
it "#proxy_update_all should update array of docs" do
docs = [{}, {}]
@obj.should_receive(:proxy_update).twice.with({})
@obj.send(:proxy_update_all, docs)
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
describe "scenarios" do
before :all do
class ProxyableCompany < CouchRest::Model::Base
use_database DB
property :slug
proxy_for :proxyable_invoices
def proxy_database
@db ||= TEST_SERVER.database!(TESTDB + "-#{slug}")
end
end
class ProxyableInvoice < CouchRest::Model::Base
property :client
property :total
proxied_by :proxyable_company
validates_uniqueness_of :client
design do
view :by_total
end
end
@company = ProxyableCompany.create(:slug => 'samco')
end
it "should create the new database" do
@company.proxyable_invoices.all.should be_empty
TEST_SERVER.databases.find{|db| db =~ /#{TESTDB}-samco/}.should_not be_nil
end
it "should allow creation of new entries" do
inv = @company.proxyable_invoices.new(:client => "Lorena", :total => 35)
# inv.database.should_not be_nil
inv.save.should be_true
@company.proxyable_invoices.count.should eql(1)
@company.proxyable_invoices.first.client.should eql("Lorena")
end
it "should validate uniqueness" do
inv = @company.proxyable_invoices.new(:client => "Lorena", :total => 40)
inv.save.should be_false
end
it "should allow design views" do
item = @company.proxyable_invoices.by_total.key(35).first
item.client.should eql('Lorena')
end
end
end

Some files were not shown because too many files have changed in this diff Show more