diff --git a/.gitignore b/.gitignore index 1759ffb..fea3188 100644 --- a/.gitignore +++ b/.gitignore @@ -8,4 +8,3 @@ couchdb.std* *.*~ Gemfile.lock spec.out -*.gem diff --git a/README.md b/README.md index 1e2b69b..1c90fdc 100644 --- a/README.md +++ b/README.md @@ -3,16 +3,6 @@ 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. @@ -21,13 +11,13 @@ it is not possible to load ActiveModel into programs that do not use ActiveSuppo CouchRest Model is only properly tested on CouchDB version 1.0 or newer. -*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: +*WARNING:* As of April 2011 and the release of version 1.1.0, the default model type key is 'model' instead of 'couchrest-type'. Simply updating your project will not work unless you migrate your data or set the configuration option in your initializers: 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. +This is because CouchRest Model's are not couchrest specific and may be used in any other system such as a Javascript library, the model type should reflect this. ## Install @@ -41,43 +31,44 @@ If you're using bundler, define a line similar to the following in your project' gem 'couchrest_model' -### Configuration +You might also consider using the latest git repository. We try to make sure the current version in git is stable and at the very least all tests should pass. -CouchRest Model is configured to work out the box with no configuration as long as your CouchDB instance is running on the default port (5984) on localhost. The default name of the database is either the name of your application as provided by the `Rails.application.class.to_s` call (with /application removed) or just 'couchrest' if none is available. + gem 'couchrest_model', :git => 'git://github.com/couchrest/couchrest_model.git' -The library will try to detect a configuration file at `config/couchdb.yml` from the Rails root or `Dir.pwd`. Here you can configuration your database connection in a Rails-like way: +### Setup - development: - protocol: 'https' - host: sample.cloudant.com - port: 443 - prefix: project - suffix: test - username: test - password: user +There is currently no standard way for telling CouchRest Model how it should access your database, this is something we're still working on. For the time being, the easiest way is to set a COUCHDB_DATABASE global variable to an instance of CouchRest Database, and call `use_database COUCHDB_DATABASE` in each model. -Note that the name of the database is either just the prefix and suffix combined or the prefix plus any text you specifify using `use_database` method in your models with the suffix on the end. +TODO: Add an example! -The example config above for example would use a database called "project_test". Heres an example using the `use_database` call: +### Development - class Project < CouchRest::Model::Base - use_database 'sample' - end +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: - # The database object would be provided as: - Project.database #=> "https://test:user@sample.cloudant.com:443/project_sample_test" + 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. ## Generators -### Configuration - - $ rails generate couchrest_model:config - ### Model - $ rails generate model person --orm=couchrest_model + $ rails generate model person --orm=couchrest_model +## Useful links and extensions + +Try some of these gems that add extra funcionality to couchrest_model: + +* [memories](http://github.com/moonmaster9000/memories) - object versioning using attachments (Matt Parker) +* [couch_publish](http://github.com/moonmaster9000/couch_publish) - versioned state machine for draft and published documents (Matt Parker) +* [couch_photo](http://github.com/moonmaster9000/couch_photo) - attach images to documents with variations (Matt Parker) +* [copycouch](http://github.com/moonmaster9000/copycouch) - single document replication on documents (Matt Parker) +* [recloner](https://github.com/moonmaster9000/recloner) - clone documents easily (Matt Parker) +* [couchrest_localised_properties](https://github.com/samlown/couchrest_localised_properties) - Transparent support for localised properties (Sam Lown) + +If you have an extension that you'd us to add to this list, please get in touch! + ## General Usage require 'couchrest_model' @@ -109,22 +100,533 @@ 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: +A property is the definition of an attribute, it describes what the attribute is called, how it should +be type casted and other options such as the default value. These replace your typical +`add_column` methods found in relational database migrations. - bundle install +Attributes with a property definition will have setter and getter methods defined for them. Any other attibute +can be set as if the model were a Hash, this funcionality is inherited from CouchRest Documents. -That should set everything up for `rake spec` to be run correctly. Update the couchrest_model.gemspec if your alterations -use different gems. +Here are a few examples of the way properties are used: -### Testing + class Cat < CouchRest::Model::Base + property :name + property :birthday + end -The most complete documentation is the spec/ directory. To validate your CouchRest install, from the project root directory run `bundle install` to ensure all the development dependencies are available and then `rspec spec` or `bundle exec rspec spec`. + @cat = Cat.new(:name => 'Felix', :birthday => 2.years.ago) + @cat.name # 'Felix' + @cat.birthday.is_a?(Time) # True! + @cat.save + @cat = Cat.find(@cat.id) + @cat.name # 'Felix' + @cat.birthday.is_a?(Time) # False! + +Properties create getters and setters similar to the following: + + def name + read_attribute('name') + end + + def name=(value) + write_attribute('name', value) + end + +Properties can also have a type which will be used for casting data retrieved from CouchDB when the attribute is set: + + class Cat < CouchRest::Model::Base + property :name, String + property :last_fed_at, Time + end + + @cat = Cat.new(:name => 'Felix', :last_fed_at => 10.minutes.ago) + @cat.last_fed_at.is_a?(Time) # True! + @cat.save + @cat = Cat.find(@cat.id) + @cat.last_fed_at < 20.minutes.ago # True! + + +Boolean or TrueClass types will create a getter with question mark at the end: + + class Cat < CouchRest::Model::Base + property :awake, TrueClass, :default => true + end + + @cat.awake? # true + +Adding the `:default` option will ensure the attribute always has a value. + +A read-only property will only have a getter method, and its value is set when the document +is read from the database. You can however update a read-only attribute using the `write_attribute` method: + + class Cat < CouchRest::Model::Base + property :name, String + property :lives, Integer, :default => 9, :readonly => true + + def fall_off_balcony! + write_attribute(:lives, lives - 1) + save + end + end + + @cat = Cat.new(:name => "Felix") + @cat.fall_off_balcony! + @cat.lives # Now 8! + +Mass assigning attributes is also possible in a similar fashion to ActiveRecord: + + @cat.attributes = { :name => "Felix" } + @cat.save + +Is the same as: + + @cat.update_attributes(:name => "Felix") + +By default, attributes without a property will not be updated via the `#attributes=` method. This provents useless data being passed to database, for example from an HTML form. However, if you would like truely +dynamic attributes, the `mass_assign_any_attribute` configuration option when set to true will +store everything you put into the `Base#attributes=` method. + + +## Property Arrays + +An attribute may contain an array of data. CouchRest Model handles this, along +with casting, by defining the class of the child attributes inside an Array: + + class Cat < CouchRest::Model::Base + property :name, String + property :nicknames, [String] + end + +By default, the array will be ready to use from the moment the object as been instantiated: + + @cat = Cat.new(:name => 'Fluffy') + @cat.nicknames << 'Buffy' + + @cat.nicknames == ['Buffy'] + +When anything other than a string is set as the class of a property, the array will be converted +into special wrapper called a CastedArray. If the child objects respond to the `casted_by` method +(such as those created with CastedModel, below) it will contain a reference to the parent. + +## Casted Models + +CouchRest Model allows you to take full advantage of CouchDB's ability to store complex +documents and retrieve them using the CastedModel module. Simply include the module in +a Hash (or other model that responds to the [] and []= methods) and set any properties +you'd like to use. For example: + + class CatToy < Hash + include CouchRest::Model::CastedModel + + property :name, String + property :purchased, Date + end + + class Cat < CouchRest::Model::Base + property :name, String + property :toys, [CatToy] + end + + @cat = Cat.new(:name => 'Felix', :toys => [{:name => 'mouse', :purchased => 1.month.ago}]) + @cat.toys.first.class == CatToy + @cat.toys.first.name == 'mouse' + +Any hashes sent to the property will automatically be converted: + + @cat.toys << {:name => 'catnip ball'} + @cat.toys.last.is_a?(CatToy) # True! + +To use your own classes they *must* be defined before the parent uses them otherwise +Ruby will bring up a missing constant error. To avoid this, or if you have a really simple array of data +you'd like to model, CouchRest Model supports creating anonymous classes: + + class Cat < CouchRest::Model::Base + property :name, String + + property :toys do + property :name, String + property :rating, Integer + end + end + + @cat = Cat.new(:name => 'Felix', :toys => [{:name => 'mouse', :rating => 3}, {:name => 'catnip ball', :rating => 5}]) + @cat.toys.last.rating == 5 + @cat.toys.last.name == 'catnip ball' + +Anonymous classes will *only* create arrays of objects. If you're more of the traditional type, a block parameter +can be provided allowing you to use this variable before each method call inside the anonymous class. This is useful +if you need to access variables outside of the block. + +## Views + +CouchDB views can be quite difficult to get grips with at first as they are quite different from what you'd expect with SQL queries in a normal Relational Database. Checkout some of the [CouchDB documentation on views](http://wiki.apache.org/couchdb/Introduction_to_CouchDB_views) to get to grips with the basics. The key is to remember that CouchDB will only generate indexes from which you can extract consecutive rows of data, filtering other than between two points in a data set is not possible. + +CouchRest Model has great support for views, and since version 1.1.0 we added support for a View objects that make accessing your data even easier. + +### The Old Way + +Here's an example of adding a view to our Cat class: + + class Cat < CouchRest::Model::Base + property :name, String + property :toys, [CatToy] + + view_by :name + end + +The `view_by` method will create a view in the Cat's design document called "by_name". This will allow searches to be made for the Cat's name attribute. Calling `Cat.by_name` will send a query of to the database and return an array of all the Cat objects available. Internally, a map function is generated automatically and stored in CouchDB's design document for the current model, it'll look something like the following: + + function(doc) { + if (doc['couchrest-type'] == 'Cat' && doc['name']) { + emit(doc.name, null); + } + } + +By default, a special view called `all` is created and added to all couchrest models that allows you access to all the documents in the database that match the model. By default, these will be ordered by each documents id field. + +It is also possible to create views of multiple keys, for example: + + view_by :birthday, :name + +This will create an view of all the cats' birthdays and their names called `by_birthday_and_name`. + +Sometimes the automatically generate map function might not be sufficient for more complicated queries. To customize, add the :map and :reduce functions when creating the view: + + view_by :tags, + :map => + "function(doc) { + if (doc['model'] == 'Post' && doc.tags) { + doc.tags.forEach(function(tag){ + emit(doc.tag, 1); + }); + } + }", + :reduce => + "function(keys, values, rereduce) { + return sum(values); + }" + +Calling a view will return document objects by default, to get access to the raw CouchDB result add the `:raw => true` option to get a hash instead. Custom views can also be queried with `:reduce => true` to return reduce results. The default is to query with `:reduce => false`. + +Views are generated (on a per-model basis) lazily on first-access. This means that if you are deploying changes to a view, the views for +that model won't be available until generation is complete. This can take some time with large databases. Strategies are in the works. + +### View Objects + +Since CouchRest Model 1.1.0 it is now possible to create views that return objects chainable objects, similar to those you'd find in the Sequel Ruby library or Rails 3's Arel. Heres an example of creating a few views: + + class Post < CouchRest::Model::Base + property :title + property :body + property :posted_at, DateTime + property :tags, [String] + + design do + view :by_title + view :by_posted_at_and_title + view :tag_list, + :map => + "function(doc) { + if (doc['model'] == 'Post' && doc.tags) { + doc.tags.forEach(function(tag){ + emit(doc.tag, 1); + }); + } + }", + :reduce => + "function(keys, values, rereduce) { + return sum(values); + }" + end + +You'll see that this new syntax requires all views to be defined inside a design block. Unlike the old version, the keys to be used in a query are determined from the name of the view, not the other way round. Acessing data is the fun part: + + # Prepare a query: + view = Post.by_posted_at_and_title.skip(5).limit(10) + + # Fetch the results: + view.each do |post| + puts "Title: #{post.title}" + end + + # Grab the CouchDB result information with the same object: + view.total_rows => 10 + view.offset => 5 + + # Re-use and add new filters + filter = view.startkey([1.month.ago]).endkey([Date.current, {}]) + + # Fetch row results without the documents: + filter.rows.each do |row| + puts "Row value: #{row.value} Doc ID: #{row.id}" + end + + # Lazily load documents (take last row from previous example): + row.doc => Fetch last Post document from database + + # Using reduced queries is also easy: + tag_usage = Post.tag_list.reduce.group_level(1) + tag_usage.rows.each do |row| + puts "Tag: #{row.key} Uses: #{row.value}" + end + +#### Pagination + +The view objects have built in support for pagination based on the [kaminari](https://github.com/amatsuda/kaminari) gem. Methods are provided to match those required by the library to peform pagination. + +For your view to support paginating the results, it must use a reduce function that provides a total count of the documents in the result set. By default, auto-generated views include a reduce function that supports this. + +Use pagination as follows: + + # Prepare a query: + @posts = Post.by_title.page(params[:page]).per(10) + + # In your view, with the kaminari gem loaded: + paginate @posts + +### Design Documents and Views + +Views must be defined in a Design Document for CouchDB to be able to perform searches. Each model therefore must have its own Design Document. Deciding when to update the model's design doc is a difficult issue, as in production you don't want to be constantly checking for updates and in development maximum flexability is important. CouchRest Model solves this issue by providing the `auto_update_design_doc` configuration option and is true by default. + +Each time a view or other design method is requested a quick GET for the design will be sent to ensure it is up to date with the latest changes. Results are cached in the current thread for the complete design document's URL, including the database, to try and limit requests. This should be fine for most projects, but dealing with multiple sub-databases may require a different strategy. + +Setting the option to false will require a manual update of each model's design doc whenever you know a change has happened. This will be useful in cases when you do not want CouchRest Model to interfere with the views already store in the CouchRest database, or you'd like to deploy your own update strategy. Here's an example of a module that will update all submodules: + + module CouchRestMigration + def self.update_design_docs + CouchRest::Model::Base.subclasses.each{|klass| klass.save_design_doc! if klass.respond_to?(:save_design_doc!)} + end + end + + # Running this from your applications initializers would be a good idea, + # for example in Rail's application.rb or environments/production.rb: + config.after_initialize do + CouchRestMigration.update_design_docs + end + +If you're dealing with multiple databases, using proxied models, or databases that are created on-the-fly, a more sophisticated approach might be required: + + module CouchRestMigration + def self.update_all_design_docs + update_design_docs(COUCHREST_DATABASE) + Company.all.each do |company| + update_design_docs(company.proxy_database) + end + end + def self.update_design_docs(db) + CouchRest::Model::Base.subclasses.each{|klass| klass.save_design_doc!(db) if klass.respond_to?(:save_design_doc!} + end + end + + # Command to run after a capistrano migration: + $ rails runner "CouchRestMigratin.update_all_design_docs" + + +## Assocations + +Two types at the moment: + + belongs_to :person + + collection_of :tags + +This is a somewhat controvesial feature of CouchRest Model that some document database purists may cringe at. CouchDB does not yet povide many features to support relationships between documents but the fact of that matter is that its a very useful paradigm for modelling data systems. + +In the near future we hope to add support for a `has_many` relationship that takes of the _Linked Documents_ feature that arrived in CouchDB 0.11. + +### Belongs To + +Creates a property in the document with `_id` added to the end of the name of the foreign model with getter and setter methods to access the model. + +Example: + + class Cat < CouchRest::Model::Base + belongs_to :mother + property :name + end + + kitty = Cat.new(:name => "Felix") + kitty.mother = Mother.find_by_name('Sophie') + +Providing a object to the setter, `mother` in the example will automagically update the `mother_id` attribute. Retrieving the data later is just as expected: + + kitty = Cat.find_by_name "Felix" + kitty.mother.name == 'Sophie' + +Belongs_to accepts a few options to add a bit more felxibility: + +* `:class_name` - the camel case string name of the class used to load the model. +* `:foreign_key` - the name of the property to use instead of the attribute name with `_id` on the end. +* `:proxy` - a string that when evaluated provides a proxy model that responds to `#get`. + +The last option, `:proxy` is a feature currently in testing that allows objects to be loaded from a proxy class, such as `ClassProxy`. For example: + + class Invoice < CouchRest::Model::Base + attr_accessor :company + belongs_to :project, :proxy => 'self.company.projects' + end + +A project instance in this scenario would need to be loaded by calling `#get(project_id)` on `self.company.projects` in the scope of an instance of the Invoice. We hope to document and work on this powerful feature in the near future. + + +### Collection Of + +A collection_of relationship is much like belongs_to except that rather than just one foreign key, an array of foreign keys can be stored. This is one of the great features of a document database. This relationship uses a proxy object to automatically update two arrays; one containing the objects being used, and a second with the foreign keys used to the find them. + +The best example of this in use is with Labels: + + class Invoice < CouchRest::Model::Base + collection_of :labels + end + + invoice = Invoice.new + invoice.labels << Label.get('xyz') + invoice.labels << Label.get('abc') + + invoice.labels.map{|l| l.name} # produces ['xyz', 'abc'] + +See the belongs_to relationship for the options that can be used. Note that this isn't especially efficient, a `get` is performed for each model in the array. As with a has_many relationship, we hope to be able to take advantage of the Linked Documents feature to avoid multiple requests. + + +## Validations + +CouchRest Model automatically includes the new ActiveModel validations, so they should work just as the traditional Rails validations. For more details, please see the ActiveModel::Validations documentation. + +CouchRest Model adds the possibility to check the uniqueness of attributes using the `validates_uniqueness_of` class method, for example: + + class Person < CouchRest::Model::Base + property :title, String + + validates_uniqueness_of :title + end + +The uniqueness validation creates a new view for the attribute or uses one that already exists. You can +specify a different view using the `:view` option, useful for when the `unique_id` is specified and +you'd like to avoid the typical RestClient Conflict error: + + unique_id :code + validates_uniqueness_of :code, :view => 'all' + +Given that the uniqueness check performs a request to the database, it is also possible to include a `:proxy` parameter. This allows you to call a method on the document and provide an alternate proxy object. + +Examples: + + # Same as not including proxy: + validates_uniqueness_of :title, :proxy => 'class' + + # Person#company.people provides a proxy object for people + validates_uniqueness_of :title, :proxy => 'company.people' + + +A really interesting use of `:proxy` and `:view` together could be where you'd like to ensure the ID is unique between several types of document. For example: + + class Product < CouchRest::Model::Base + property :code + + validates_uniqueness_of :code, :view => 'by_product_code' + + view_by :product_code, :map => " + function(doc) { + if (doc['couchrest-type'] == 'Product' || doc['couchrest-type'] == 'Project') { + emit(doc['code']); + } + } + " + end + + class Project < CouchRest::Model::Base + property :code + + validates_uniqueness_of :code, :view => 'by_product_code', :proxy => 'Product' + end + +Pretty cool! + +## Proxy Support + +CouchDB makes it really easy to create databases on the fly, so easy in fact that it is perfectly +feasable to have one database per user or per company or per whatever makes sense to split into +its own individual database. CouchRest Model now makes it really easy to support this scenario +using the proxy methods. Here's a quick example: + + # Define a master company class, its children should be in their own DB + class Company < CouchRest::Model::Base + use_database COUCHDB_DATABASE + property :name + property :slug + + proxy_for :invoices + + def proxy_database + @proxy_database ||= COUCHDB_SERVER.database!("project_#{slug}") + end + end + + # Invoices belong to a company + class Invoice < CouchRest::Model::Base + property :date + property :total + + proxied_by :company + + design do + view :by_date + end + end + +By setting up our models like this, the invoices should be accessed via a company object: + + company = Company.first + company.invoices.new # build a new invoice + company.invoices.by_date.first # find company's first invoice by date + +Internally, all requests for invoices are passed through a model proxy. Aside from the +basic methods and views, it also ensures that some of the more complex queries are supported +such as validating for uniqueness and associations. + + +## Configuration + +CouchRest Model supports a few configuration options. These can be set either for the whole Model code +base or for a specific model of your chosing. To configure globally, provide something similar to the +following in your projects initializers or environments: + + CouchRest::Model::Base.configure do |config| + config.mass_assign_any_attribute = true + config.model_type_key = 'couchrest-type' + end + +To set for a specific model: + + class Cat < CouchRest::Model::Base + mass_assign_any_attribute true + end + +Options currently avilable are: + + * `mass_assign_any_attribute` - false by default, when true any attribute may be updated via the update_attributes or attributes= methods. + * `model_type_key` - 'model' by default, is the name of property that holds the class name of each CouchRest Model. + * `auto_update_design_doc` - true by default, every time a view is requested and this option is true, a quick check will be performed to ensure the model's design document is up to date. When disabled, you're design documents will never be updated automatically and you'll need to perform updates manually. Results are cached on a per-database and per-design basis to help lower the number of requests. See the View section for more details. + + +## Notable Issues + +None at the moment... + + +## Testing + +The most complete documentation is the spec/ directory. To validate your CouchRest install, from the project root directory run `rake`, or `autotest` (requires RSpec and optionally ZenTest for autotest support). + +## Docs + +API: [http://rdoc.info/projects/couchrest/couchrest_model](http://rdoc.info/projects/couchrest/couchrest_model) + +Check the wiki for documentation and examples [http://wiki.github.com/couchrest/couchrest_model](http://wiki.github.com/couchrest/couchrest_model) -We will not accept pull requests to the project without sufficient tests. ## Contact @@ -134,4 +636,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) - diff --git a/Rakefile b/Rakefile index f624098..8cf05ec 100644 --- a/Rakefile +++ b/Rakefile @@ -1,20 +1,23 @@ require 'rubygems' require 'bundler' -require 'rspec/core/rake_task' -require "rake/rdoctask" - Bundler::GemHelper.install_tasks +require 'rake' +require "rake/rdoctask" + +require 'rspec' +require 'rspec/core/rake_task' + desc "Run all specs" -RSpec::Core::RakeTask.new(:spec) do |spec| - spec.rspec_opts = ["--color"] - spec.pattern = 'spec/**/*_spec.rb' +Rspec::Core::RakeTask.new(:spec) do |spec| + spec.rspec_opts = ["--color"] + spec.pattern = 'spec/**/*_spec.rb' end desc "Print specdocs" -RSpec::Core::RakeTask.new(:doc) do |spec| - spec.rspec_opts = ["--format", "specdoc"] - spec.pattern = 'spec/*_spec.rb' +Rspec::Core::RakeTask.new(:doc) do |spec| + spec.rspec_opts = ["--format", "specdoc"] + spec.pattern = 'spec/*_spec.rb' end desc "Generate the rdoc" @@ -35,4 +38,4 @@ module Rake end Rake.remove_task("github:release") -Rake.remove_task("release") \ No newline at end of file +Rake.remove_task("release") diff --git a/VERSION b/VERSION index 45a1b3f..f1916af 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.1.2 +1.1.0.beta4 diff --git a/couchrest_model.gemspec b/couchrest_model.gemspec index cc22676..0344b97 100644 --- a/couchrest_model.gemspec +++ b/couchrest_model.gemspec @@ -6,7 +6,7 @@ Gem::Specification.new do |s| s.required_rubygems_version = Gem::Requirement.new("> 1.3.1") if s.respond_to? :required_rubygems_version= s.authors = ["J. Chris Anderson", "Matt Aimonetti", "Marcos Tapajos", "Will Leinweber", "Sam Lown"] - s.date = File.mtime('VERSION') + s.date = %q{2011-01-16} s.description = %q{CouchRest Model provides aditional features to the standard CouchRest Document class such as properties, view designs, associations, callbacks, typecasting and validations.} s.email = %q{jchris@apache.org} s.extra_rdoc_files = [ @@ -17,20 +17,19 @@ Gem::Specification.new do |s| 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.require_paths = ["lib"] - - s.add_dependency(%q, "~> 1.1.2") + + s.add_dependency(%q, "1.1.0.pre2") s.add_dependency(%q, "~> 1.15") - s.add_dependency(%q, "~> 3.0") + s.add_dependency(%q, "~> 3.0.5") s.add_dependency(%q, "~> 0.3.22") - s.add_development_dependency(%q, "~> 2.6.0") - s.add_development_dependency(%q, ["~> 1.5.1"]) + s.add_dependency(%q, "~> 3.0.0") + s.add_development_dependency(%q, ">= 2.0.0") s.add_development_dependency(%q, ">= 0.5.7") - s.add_development_dependency("rake", ">= 0.8.0") # s.add_development_dependency("jruby-openssl", ">= 0.7.3") end diff --git a/history.md b/history.txt similarity index 77% rename from history.md rename to history.txt index a8b18ce..dc71b9b 100644 --- a/history.md +++ b/history.txt @@ -1,67 +1,4 @@ -# 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 +== 1.1.0.beta4 * Major changes: * Fast Dirty Tracking! Many thanks to @sobakasu (Andrew Williams) @@ -73,11 +10,11 @@ * Added "auto_update_design_doc" configuration option. * Using #descending on View object will automatically swap startkey with endkey. -## 1.1.0.beta3 +== 1.1.0.beta3 * Removed -## 1.1.0.beta2 +== 1.1.0.beta2 * Minor enhancements: * Time handling improved in accordance with CouchRest 1.1.0. Always set to UTC. @@ -86,7 +23,7 @@ * Unique Validation now supports scopes! * Added support for #keys with list on Design View. -## 1.1.0.beta +== 1.1.0.beta * Epic enhancements: * Added "View" object for dynamic view queries @@ -100,7 +37,7 @@ * 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 +== CouchRest Model 1.0.0 * Major enhancements * Support for configuration module and "model_type_key" option for overriding model's type key @@ -119,7 +56,7 @@ Notes: 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 +== CouchRest Model 1.0.0.beta8 * Major enhancements * Added model generator @@ -130,7 +67,7 @@ Notes: * 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 @@ -146,7 +83,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 +97,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 +112,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,12 +125,12 @@ 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) @@ -203,7 +140,7 @@ Notes: * 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 +156,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 @@ -244,7 +181,7 @@ 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 @@ -259,7 +196,7 @@ 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 @@ -274,7 +211,7 @@ Notes: * 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 @@ -288,7 +225,7 @@ Notes: * Optimized ExtendedDocument.count to run about 3x faster (Matt Aimonetti) * Added Float casting (Ryan Felton & Matt Aimonetti) -## 0.30 +== 0.30 * Major enhancements diff --git a/lib/couchrest/model/associations.rb b/lib/couchrest/model/associations.rb index e98e48e..ed2c23c 100644 --- a/lib/couchrest/model/associations.rb +++ b/lib/couchrest/model/associations.rb @@ -153,7 +153,7 @@ module CouchRest 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) + @#{attrib} = ::CouchRest::CollectionOfProxy.new(ary, self, '#{options[:foreign_key]}') end EOS end @@ -161,7 +161,7 @@ module CouchRest def create_collection_of_setter(attrib, 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 +169,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 diff --git a/lib/couchrest/model/base.rb b/lib/couchrest/model/base.rb index 40cb968..e70d325 100644 --- a/lib/couchrest/model/base.rb +++ b/lib/couchrest/model/base.rb @@ -1,13 +1,13 @@ 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 @@ -17,11 +17,9 @@ module CouchRest include CouchRest::Model::PropertyProtection 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 ||= [] @@ -47,24 +45,18 @@ module CouchRest # # Options supported: # - # * :directly_set_attributes, true when data comes directly from database - # * :database, provide an alternative 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 + def initialize(doc = {}, options = {}) + doc = prepare_all_attributes(doc, options) + # set the instances database, if provided self.database = options[:database] unless options[:database].nil? + super(doc) unless self['_id'] && self['_rev'] self[self.model_type_key] = self.class.to_s end - - yield self if block_given? - after_initialize if respond_to?(:after_initialize) - run_callbacks(:initialize) { self } end @@ -82,19 +74,18 @@ module CouchRest 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) - end + ## Compatibility with ActiveSupport and older frameworks - # 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]) + # 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 @@ -104,26 +95,6 @@ module CouchRest 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 diff --git a/lib/couchrest/model/callbacks.rb b/lib/couchrest/model/callbacks.rb index 18a36e9..3037810 100644 --- a/lib/couchrest/model/callbacks.rb +++ b/lib/couchrest/model/callbacks.rb @@ -5,23 +5,21 @@ 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 + end + + def valid?(*) #nodoc + _run_validation_callbacks { super } + end + end end diff --git a/lib/couchrest/model/casted_array.rb b/lib/couchrest/model/casted_array.rb index 65b7f46..6737b46 100644 --- a/lib/couchrest/model/casted_array.rb +++ b/lib/couchrest/model/casted_array.rb @@ -50,22 +50,6 @@ module CouchRest::Model super end - def delete(obj) - couchrest_parent_will_change! if use_dirty? && self.length > 0 - super(obj) - end - - def delete_at(index) - couchrest_parent_will_change! if use_dirty? && self.length > 0 - super(index) - end - - def build(*args) - obj = casted_by_property.build(*args) - self.push(obj) - obj - end - protected def instantiate_and_cast(obj, change = true) diff --git a/lib/couchrest/model/embeddable.rb b/lib/couchrest/model/casted_model.rb similarity index 71% rename from lib/couchrest/model/embeddable.rb rename to lib/couchrest/model/casted_model.rb index 05970a2..f20de16 100644 --- a/lib/couchrest/model/embeddable.rb +++ b/lib/couchrest/model/casted_model.rb @@ -1,37 +1,37 @@ module CouchRest::Model - module Embeddable - extend ActiveSupport::Concern + module CastedModel - # Include Attributes early to ensure super() will work - include CouchRest::Attributes + extend ActiveSupport::Concern included do include CouchRest::Model::Configuration + 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 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 # False if the casted model has already @@ -65,14 +65,6 @@ module CouchRest::Model 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 diff --git a/lib/couchrest/model/class_proxy.rb b/lib/couchrest/model/class_proxy.rb index 16887a3..3f988b1 100644 --- a/lib/couchrest/model/class_proxy.rb +++ b/lib/couchrest/model/class_proxy.rb @@ -87,14 +87,7 @@ module CouchRest 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) diff --git a/lib/couchrest/model/collection.rb b/lib/couchrest/model/collection.rb index 5d6dd76..540b299 100644 --- a/lib/couchrest/model/collection.rb +++ b/lib/couchrest/model/collection.rb @@ -244,7 +244,6 @@ module CouchRest else options = { :limit => per_page, :skip => per_page * (page - 1) } end - options[:include_docs] = true view_options.merge(options) end diff --git a/lib/couchrest/model/configuration.rb b/lib/couchrest/model/configuration.rb index 323dfd7..027bf3c 100644 --- a/lib/couchrest/model/configuration.rb +++ b/lib/couchrest/model/configuration.rb @@ -11,27 +11,11 @@ module CouchRest 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.model_type_key = 'model' # 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 diff --git a/lib/couchrest/model/connection.rb b/lib/couchrest/model/connection.rb deleted file mode 100644 index d85debe..0000000 --- a/lib/couchrest/model/connection.rb +++ /dev/null @@ -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 diff --git a/lib/couchrest/model/design_doc.rb b/lib/couchrest/model/design_doc.rb index 36c3940..edcb043 100644 --- a/lib/couchrest/model/design_doc.rb +++ b/lib/couchrest/model/design_doc.rb @@ -7,11 +7,7 @@ module CouchRest 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 ||= ::CouchRest::Design.new(default_design_doc) end def design_doc_id @@ -79,25 +75,16 @@ module CouchRest # 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) + # 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) end - rescue RestClient::Conflict - # if we get a conflict retry the operation... - raise if retries < 1 - retries -= 1 - retry + else + db.save_doc(design_doc) + design_doc.delete('_rev') # Prevent conflicts, never store rev as DB specific end # Ensure checksum cached for next attempt if using auto updates @@ -121,6 +108,8 @@ module CouchRest } end + + end # module ClassMethods end diff --git a/lib/couchrest/model/designs.rb b/lib/couchrest/model/designs.rb index 3862567..ddc157a 100644 --- a/lib/couchrest/model/designs.rb +++ b/lib/couchrest/model/designs.rb @@ -58,25 +58,13 @@ module CouchRest 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. + # Define a view and generate a method that will provide a new + # View instance when requested. def view(name, opts = {}) - View.create(model, name, opts) if model.auto_update_design_doc + View.create(model, name, opts) 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 = {}) diff --git a/lib/couchrest/model/document_queries.rb b/lib/couchrest/model/document_queries.rb index 22aec40..af1083d 100644 --- a/lib/couchrest/model/document_queries.rb +++ b/lib/couchrest/model/document_queries.rb @@ -1,10 +1,13 @@ 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 # name of the current class. Take the standard set of # CouchRest::Database#view options. @@ -70,7 +73,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 +86,9 @@ module CouchRest # id:: Document ID # db:: optional option to pass a custom database to use def get!(id, db = database) - raise CouchRest::Model::DocumentNotFound if id.blank? - + raise "Missing or empty document ID" if id.to_s.empty? doc = db.get id build_from_database(doc) - rescue RestClient::ResourceNotFound - raise CouchRest::Model::DocumentNotFound end alias :find! :get! diff --git a/lib/couchrest/model/errors.rb b/lib/couchrest/model/errors.rb index 45d8b2f..7f14fca 100644 --- a/lib/couchrest/model/errors.rb +++ b/lib/couchrest/model/errors.rb @@ -19,7 +19,5 @@ module CouchRest end end end - - class DocumentNotFound < Errors::CouchRestModelError; end end end diff --git a/lib/couchrest/model/persistence.rb b/lib/couchrest/model/persistence.rb index a9e0a75..4f19e86 100644 --- a/lib/couchrest/model/persistence.rb +++ b/lib/couchrest/model/persistence.rb @@ -21,15 +21,14 @@ module CouchRest # 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 @@ -55,25 +54,19 @@ module CouchRest end # Deletes the document from the database. Runs the :destroy callbacks. + # Removes the _id and _rev fields, preparing the + # document to be saved to a new _id 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" @@ -92,10 +85,11 @@ module CouchRest # # Returns self. def reload - prepare_all_attributes(database.get(id), :directly_set_attributes => true) + merge!(self.class.get(id)) self end + protected def perform_validations(options = {}) @@ -111,25 +105,22 @@ 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 build_from_database(doc = {}) + base = (doc[model_type_key].blank? || doc[model_type_key] == self.to_s) ? self : doc[model_type_key].constantize + base.new(doc, :directly_set_attributes => true) end # 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 @@ -138,8 +129,8 @@ module CouchRest # # ==== 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 diff --git a/lib/couchrest/model/properties.rb b/lib/couchrest/model/properties.rb index 54cfb71..5e8a13d 100644 --- a/lib/couchrest/model/properties.rb +++ b/lib/couchrest/model/properties.rb @@ -5,17 +5,25 @@ module CouchRest 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) + extlib_inheritable_accessor(:properties) unless self.respond_to?(:properties) + extlib_inheritable_accessor(: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?(:[]=)) 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?} + # Returns the Class properties + # + # ==== Returns + # Array:: the list of properties for model's class + def properties + self.class.properties + end + + # Returns all the class's properties as a Hash where the key is the name + # of the property. + def properties_by_name + self.class.properties_by_name end # Returns the Class properties with their values @@ -82,18 +90,17 @@ module CouchRest self.disable_dirty = dirty end - def prepare_all_attributes(attrs = {}, options = {}) + def prepare_all_attributes(doc = {}, 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) + directly_set_read_only_attributes(doc) else - attrs = remove_protected_attributes(attrs) - directly_set_attributes(attrs) + doc = remove_protected_attributes(doc) end + res = doc.nil? ? doc : directly_set_attributes(doc) self.disable_dirty = false - self + res end def find_property!(property) @@ -104,13 +111,16 @@ module CouchRest # 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 + def directly_set_attributes(hash) + hash.reject do |attribute_name, attribute_value| + if self.respond_to?("#{attribute_name}=") + self.send("#{attribute_name}=", attribute_value) + true + elsif mass_assign_any_attribute # config option + self[attribute_name] = attribute_value + true + else + false end end end @@ -130,7 +140,7 @@ module CouchRest 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 + raise "Invalid property definition, '#{name}' already used for CouchRest Model type field" if name.to_s == model_type_key.to_s opts = { } type = options.shift if type.class != Hash @@ -151,13 +161,15 @@ module CouchRest # These properties are casted as Time objects, so they should always # be set to UTC. 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) + 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 + 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 @@ -168,8 +180,8 @@ module CouchRest # 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 + type = Class.new(Hash) do + include CastedModel end if block.arity == 1 # Traditional, with options type.class_eval { yield type } @@ -191,32 +203,42 @@ module CouchRest # 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 diff --git a/lib/couchrest/model/property.rb b/lib/couchrest/model/property.rb index 6058fda..baa71ce 100644 --- a/lib/couchrest/model/property.rb +++ b/lib/couchrest/model/property.rb @@ -27,15 +27,19 @@ 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) + # Assume provided as a Hash where key is index! + data = value + value = [ ] + data.keys.sort.each do |k| + value << data[k] + end elsif !value.is_a?(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)) + elsif (type == Object || type == Hash) && (value.class == Hash) # allow casted_by calls to be passed up chain by wrapping in CastedHash CastedHash[value, self, parent] elsif !value.nil? @@ -43,8 +47,9 @@ module CouchRest::Model end 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 @@ -59,28 +64,8 @@ module CouchRest::Model 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) diff --git a/lib/couchrest/model/proxyable.rb b/lib/couchrest/model/proxyable.rb index 9fb812c..81b30b5 100644 --- a/lib/couchrest/model/proxyable.rb +++ b/lib/couchrest/model/proxyable.rb @@ -4,14 +4,8 @@ module CouchRest 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 = {}) @@ -19,19 +13,19 @@ module CouchRest options[:class_name] ||= assoc_name.to_s.singularize.camelize class_eval <<-EOS, __FILE__, __LINE__ + 1 def #{assoc_name} + unless respond_to?('#{db_method}') + raise "Missing ##{db_method} method for proxy" + end @#{assoc_name} ||= CouchRest::Model::Proxyable::ModelProxy.new(::#{options[:class_name]}, self, self.class.to_s.underscore, #{db_method}) 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 @@ -40,25 +34,6 @@ module CouchRest 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 @@ -73,12 +48,12 @@ module CouchRest end # Base - def new(attrs = {}, options = {}, &block) - proxy_block_update(:new, attrs, options, &block) + def new(*args) + proxy_update(model.new(*args)) end - def build_from_database(attrs = {}, options = {}, &block) - proxy_block_update(:build_from_database, attrs, options, &block) + def build_from_database(doc = {}) + proxy_update(model.build_from_database(doc)) end def method_missing(m, *args, &block) @@ -170,13 +145,6 @@ module CouchRest 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 diff --git a/lib/couchrest/model/support/couchrest_database.rb b/lib/couchrest/model/support/couchrest_database.rb deleted file mode 100644 index dc75bec..0000000 --- a/lib/couchrest/model/support/couchrest_database.rb +++ /dev/null @@ -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 diff --git a/lib/couchrest/model/support/couchrest_design.rb b/lib/couchrest/model/support/couchrest_design.rb index 73e9eaa..a5caf07 100644 --- a/lib/couchrest/model/support/couchrest_design.rb +++ b/lib/couchrest/model/support/couchrest_design.rb @@ -18,7 +18,7 @@ CouchRest::Design.class_eval do flatten = lambda {|r| (recurse = lambda {|v| - if v.is_a?(Hash) || v.is_a?(CouchRest::Document) + if v.is_a?(Hash) v.to_a.map{|v| recurse.call(v)}.flatten elsif v.is_a?(Array) v.flatten.map{|v| recurse.call(v)} diff --git a/lib/couchrest/model/typecast.rb b/lib/couchrest/model/typecast.rb index 6858335..6e1113d 100644 --- a/lib/couchrest/model/typecast.rb +++ b/lib/couchrest/model/typecast.rb @@ -14,7 +14,8 @@ module CouchRest 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 diff --git a/lib/couchrest/model/validations.rb b/lib/couchrest/model/validations.rb index 825b169..11a2571 100644 --- a/lib/couchrest/model/validations.rb +++ b/lib/couchrest/model/validations.rb @@ -13,33 +13,22 @@ 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 + include ActiveModel::Validations::Callbacks 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. diff --git a/lib/couchrest/model/validations/uniqueness.rb b/lib/couchrest/model/validations/uniqueness.rb index 6f9abdd..c289849 100644 --- a/lib/couchrest/model/validations/uniqueness.rb +++ b/lib/couchrest/model/validations/uniqueness.rb @@ -3,7 +3,7 @@ module CouchRest module Model module Validations - + # Validates if a field is unique class UniquenessValidator < ActiveModel::EachValidator @@ -11,33 +11,29 @@ module CouchRest # 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 end def validate_each(document, attribute, value) - opts = merge_view_options(attribute) - - values = opts[:keys].map{|k| document.send(k)} + keys = [attribute] + unless options[:scope].nil? + keys = (options[:scope].is_a?(Array) ? options[:scope] : [options[:scope]]) + keys + end + values = keys.map{|k| document.send(k)} values = values.first if values.length == 1 + view_name = options[:view].nil? ? "by_#{keys.join('_and_')}" : options[:view] + model = (document.respond_to?(:model_proxy) && document.model_proxy ? document.model_proxy : @model) # Determine the base of the search - base = opts[:proxy].nil? ? model : document.instance_eval(opts[:proxy]) + base = options[:proxy].nil? ? model : document.instance_eval(options[:proxy]) - if base.respond_to?(:has_view?) && !base.has_view?(opts[:view_name]) - 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? + keys << {:allow_nil => true} + model.view_by(*keys) end - rows = base.view(opts[:view_name], :key => values, :limit => 2, :include_docs => false)['rows'] + rows = base.view(view_name, :key => values, :limit => 2, :include_docs => false)['rows'] return if rows.empty? unless document.new? @@ -51,17 +47,6 @@ module CouchRest end end - private - - def merge_view_options(attr) - keys = [attr] - keys.unshift(*options[:scope]) unless options[:scope].nil? - - view_name = options[:view].nil? ? "by_#{keys.join('_and_')}" : options[:view] - - options.merge({:keys => keys, :view_name => view_name}) - end - end end diff --git a/lib/couchrest/model/views.rb b/lib/couchrest/model/views.rb index f8331e5..89dffbd 100644 --- a/lib/couchrest/model/views.rb +++ b/lib/couchrest/model/views.rb @@ -72,12 +72,9 @@ module CouchRest # spec/couchrest/more/extended_doc_spec.rb. 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}')" diff --git a/lib/couchrest/railtie.rb b/lib/couchrest/railtie.rb index 0c4d04a..7c55e0f 100644 --- a/lib/couchrest/railtie.rb +++ b/lib/couchrest/railtie.rb @@ -1,24 +1,12 @@ 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 +module CouchrestModel + # = Active Record Railtie + class Railtie < Rails::Railtie + config.generators.orm :couchrest_model + config.generators.test_framework :test_unit, :fixture => false end - + end - + diff --git a/lib/couchrest_model.rb b/lib/couchrest_model.rb index 699da9e..9a7a18a 100644 --- a/lib/couchrest_model.rb +++ b/lib/couchrest_model.rb @@ -1,6 +1,7 @@ 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" @@ -33,6 +34,7 @@ require "couchrest/model/property_protection" require "couchrest/model/properties" require "couchrest/model/casted_array" require "couchrest/model/casted_hash" +require "couchrest/model/casted_model" require "couchrest/model/validations" require "couchrest/model/callbacks" require "couchrest/model/document_queries" @@ -44,23 +46,19 @@ require "couchrest/model/proxyable" require "couchrest/model/collection" 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" # 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 + +require "couchrest/railtie" diff --git a/lib/rails/generators/couchrest_model/config/config_generator.rb b/lib/rails/generators/couchrest_model/config/config_generator.rb deleted file mode 100644 index b78b4d5..0000000 --- a/lib/rails/generators/couchrest_model/config/config_generator.rb +++ /dev/null @@ -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 \ No newline at end of file diff --git a/lib/rails/generators/couchrest_model/config/templates/couchdb.yml b/lib/rails/generators/couchrest_model/config/templates/couchdb.yml deleted file mode 100644 index 2216a90..0000000 --- a/lib/rails/generators/couchrest_model/config/templates/couchdb.yml +++ /dev/null @@ -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 \ No newline at end of file diff --git a/spec/unit/assocations_spec.rb b/spec/couchrest/assocations_spec.rb similarity index 88% rename from spec/unit/assocations_spec.rb rename to spec/couchrest/assocations_spec.rb index 528b5d0..cb3b0c4 100644 --- a/spec/unit/assocations_spec.rb +++ b/spec/couchrest/assocations_spec.rb @@ -1,5 +1,7 @@ # encoding: utf-8 -require 'spec_helper' +require File.expand_path('../../spec_helper', __FILE__) +require File.join(FIXTURE_PATH, 'more', 'sale_invoice') + describe "Assocations" do @@ -99,7 +101,7 @@ describe "Assocations" do it "should create an associated property and collection proxy" do @invoice.respond_to?('entry_ids').should be_true @invoice.respond_to?('entry_ids=').should be_true - @invoice.entries.class.should eql(::CouchRest::Model::CollectionOfProxy) + @invoice.entries.class.should eql(::CouchRest::CollectionOfProxy) end it "should allow replacement of objects" do @@ -152,33 +154,6 @@ 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 diff --git a/spec/unit/attachment_spec.rb b/spec/couchrest/attachment_spec.rb similarity index 99% rename from spec/unit/attachment_spec.rb rename to spec/couchrest/attachment_spec.rb index 0d050d3..420b88c 100644 --- a/spec/unit/attachment_spec.rb +++ b/spec/couchrest/attachment_spec.rb @@ -1,4 +1,4 @@ -require 'spec_helper' +require File.expand_path('../../spec_helper', __FILE__) describe "Model attachments" do diff --git a/spec/unit/base_spec.rb b/spec/couchrest/base_spec.rb similarity index 77% rename from spec/unit/base_spec.rb rename to spec/couchrest/base_spec.rb index de4a619..21c9a40 100644 --- a/spec/unit/base_spec.rb +++ b/spec/couchrest/base_spec.rb @@ -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 @@ -38,50 +44,8 @@ describe "Model Base" do @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") - end end - + describe "ActiveModel compatability Basic" do before(:each) do @@ -121,22 +85,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 +104,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 +147,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 +155,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 +170,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} @@ -321,7 +227,7 @@ describe "Model Base" do WithTemplateAndUniqueID.all.map{|o| o.destroy} 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' @@ -342,10 +248,10 @@ describe "Model Base" do before(:all) do WithTemplateAndUniqueID.all.map{|o| o.destroy} 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 find all" do rs = WithTemplateAndUniqueID.all @@ -363,9 +269,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 +280,14 @@ 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.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 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 } @@ -459,7 +365,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') diff --git a/spec/unit/embeddable_spec.rb b/spec/couchrest/casted_model_spec.rb similarity index 88% rename from spec/unit/embeddable_spec.rb rename to spec/couchrest/casted_model_spec.rb index 9b5b52e..2bed08c 100644 --- a/spec/unit/embeddable_spec.rb +++ b/spec/couchrest/casted_model_spec.rb @@ -1,25 +1,26 @@ # 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 @@ -28,8 +29,8 @@ class DummyModel < CouchRest::Model::Base 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 @@ -50,7 +51,19 @@ 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 @@ -69,27 +82,7 @@ describe CouchRest::Model::Embeddable do 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 @@ -169,33 +162,6 @@ describe CouchRest::Model::Embeddable do 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é']) diff --git a/spec/unit/casted_spec.rb b/spec/couchrest/casted_spec.rb similarity index 89% rename from spec/unit/casted_spec.rb rename to spec/couchrest/casted_spec.rb index a7b4860..44e4231 100644 --- a/spec/unit/casted_spec.rb +++ b/spec/couchrest/casted_spec.rb @@ -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 diff --git a/spec/unit/class_proxy_spec.rb b/spec/couchrest/class_proxy_spec.rb similarity index 78% rename from spec/unit/class_proxy_spec.rb rename to spec/couchrest/class_proxy_spec.rb index f945d30..f274ca9 100644 --- a/spec/unit/class_proxy_spec.rb +++ b/spec/couchrest/class_proxy_spec.rb @@ -1,4 +1,4 @@ -require "spec_helper" +require File.expand_path("../../spec_helper", __FILE__) class UnattachedDoc < CouchRest::Model::Base # Note: no use_database here @@ -123,35 +123,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. diff --git a/spec/unit/collection_spec.rb b/spec/couchrest/collection_spec.rb similarity index 92% rename from spec/unit/collection_spec.rb rename to spec/couchrest/collection_spec.rb index e501072..528a350 100644 --- a/spec/unit/collection_spec.rb +++ b/spec/couchrest/collection_spec.rb @@ -1,4 +1,5 @@ -require "spec_helper" +require File.expand_path("../../spec_helper", __FILE__) +require File.join(FIXTURE_PATH, 'more', 'article') describe "Collections" do @@ -26,20 +27,21 @@ describe "Collections" do 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) + :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) + :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) + :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 } + :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 diff --git a/spec/unit/configuration_spec.rb b/spec/couchrest/configuration_spec.rb similarity index 91% rename from spec/unit/configuration_spec.rb rename to spec/couchrest/configuration_spec.rb index 26255f9..46681c0 100644 --- a/spec/unit/configuration_spec.rb +++ b/spec/couchrest/configuration_spec.rb @@ -1,7 +1,8 @@ # encoding: utf-8 -require "spec_helper" +require File.expand_path('../../spec_helper', __FILE__) +require File.join(FIXTURE_PATH, 'more', 'cat') -describe CouchRest::Model::Configuration do +describe CouchRest::Model::Base do before do @class = Class.new(CouchRest::Model::Base) @@ -58,7 +59,7 @@ describe CouchRest::Model::Configuration do describe "General examples" do before(:all) do - @default_model_key = 'model-type' + @default_model_key = 'model' end diff --git a/spec/unit/core_extensions/time_parsing.rb b/spec/couchrest/core_extensions/time_parsing.rb similarity index 100% rename from spec/unit/core_extensions/time_parsing.rb rename to spec/couchrest/core_extensions/time_parsing.rb diff --git a/spec/unit/design_doc_spec.rb b/spec/couchrest/design_doc_spec.rb similarity index 63% rename from spec/unit/design_doc_spec.rb rename to spec/couchrest/design_doc_spec.rb index 299f5e6..7e83262 100644 --- a/spec/unit/design_doc_spec.rb +++ b/spec/couchrest/design_doc_spec.rb @@ -1,7 +1,10 @@ # encoding: utf-8 -require 'spec_helper' -describe CouchRest::Model::DesignDoc do +require File.expand_path("../../spec_helper", __FILE__) +require File.join(FIXTURE_PATH, 'base') +require File.join(FIXTURE_PATH, 'more', 'article') + +describe "Design Documents" do before :all do reset_test_db! @@ -14,11 +17,11 @@ describe CouchRest::Model::DesignDoc do end it "should calculate a consistent checksum for model" do - WithTemplateAndUniqueID.design_doc.checksum!.should eql('caa2b4c27abb82b4e37421de76d96ffc') + WithTemplateAndUniqueID.design_doc.checksum!.should eql('ff6fa2eaf774397391942d51428c1fe2') end it "should calculate checksum for complex model" do - Article.design_doc.checksum!.should eql('70dff8caea143bf40fad09adf0701104') + Article.design_doc.checksum!.should eql('fb65c06a76b6141529e31e894ad00b1a') end it "should cache the generated checksum value" do @@ -152,75 +155,42 @@ describe CouchRest::Model::DesignDoc do 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 + + before :all do + Article.auto_update_design_doc = false + Article.save_design_doc! + end - 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 + after :all do + Article.auto_update_design_doc = true + end - class_name.constantize - } + it "will not send a request for the saved design doc" do + Article.should_not_receive(:stored_design_doc) + Article.by_date + end 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']) + Article.by_date + orig = Article.stored_design_doc + design = Article.design_doc + view = design['views']['by_date']['map'] + design['views']['by_date']['map'] = view + ' ' + Article.by_date + Article.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 + Article.by_date + orig = Article.stored_design_doc + design = Article.design_doc + view = design['views']['by_date']['map'] + design['views']['by_date']['map'] = view + ' ' + Article.save_design_doc! + Article.stored_design_doc['_rev'].should_not eql(orig['_rev']) end end end @@ -228,7 +198,7 @@ describe CouchRest::Model::DesignDoc do describe "lazily refreshing the design document" do before(:all) do @db = reset_test_db! - WithTemplateAndUniqueID.new('slug' => '1').save + WithTemplateAndUniqueID.new('important-field' => '1').save end it "should not save the design doc twice" do WithTemplateAndUniqueID.all diff --git a/spec/unit/designs/view_spec.rb b/spec/couchrest/designs/view_spec.rb similarity index 99% rename from spec/unit/designs/view_spec.rb rename to spec/couchrest/designs/view_spec.rb index 572fca6..46b0d72 100644 --- a/spec/unit/designs/view_spec.rb +++ b/spec/couchrest/designs/view_spec.rb @@ -74,7 +74,7 @@ describe "Design View" do 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("((doc['model'] == 'DesignViewModel') && (doc['title'] != null))") str.should include("emit(doc['title'], 1);") str = @design_doc['views']['by_title']['reduce'] str.should include("return sum(values);") diff --git a/spec/unit/designs_spec.rb b/spec/couchrest/designs_spec.rb similarity index 73% rename from spec/unit/designs_spec.rb rename to spec/couchrest/designs_spec.rb index 96d02a3..9f578f8 100644 --- a/spec/unit/designs_spec.rb +++ b/spec/couchrest/designs_spec.rb @@ -1,9 +1,10 @@ -require "spec_helper" +require File.expand_path("../../spec_helper", __FILE__) class DesignModel < CouchRest::Model::Base + end -describe CouchRest::Model::Designs do +describe "Design" do it "should accessable from model" do DesignModel.respond_to?(:design).should be_true @@ -83,36 +84,6 @@ describe CouchRest::Model::Designs do @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 diff --git a/spec/unit/dirty_spec.rb b/spec/couchrest/dirty_spec.rb similarity index 89% rename from spec/unit/dirty_spec.rb rename to spec/couchrest/dirty_spec.rb index ceadb16..12c4f18 100644 --- a/spec/unit/dirty_spec.rb +++ b/spec/couchrest/dirty_spec.rb @@ -1,6 +1,12 @@ -require "spec_helper" +require File.expand_path("../../spec_helper", __FILE__) -class WithCastedModelMixin +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') + +class WithCastedModelMixin < Hash include CouchRest::Model::CastedModel property :name property :details, Object, :default => {} @@ -235,14 +241,6 @@ describe "Dirty" do 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 @@ -251,50 +249,6 @@ describe "Dirty" do 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") diff --git a/spec/couchrest/inherited_spec.rb b/spec/couchrest/inherited_spec.rb new file mode 100644 index 0000000..69eba6a --- /dev/null +++ b/spec/couchrest/inherited_spec.rb @@ -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 diff --git a/spec/unit/persistence_spec.rb b/spec/couchrest/persistence_spec.rb similarity index 83% rename from spec/unit/persistence_spec.rb rename to spec/couchrest/persistence_spec.rb index e8f78ac..86ded62 100644 --- a/spec/unit/persistence_spec.rb +++ b/spec/couchrest/persistence_spec.rb @@ -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 @@ -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 @@ -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 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 @@ -356,27 +340,6 @@ describe CouchRest::Model::Persistence do end end - describe "with contextual validation on ”create”" do - it "should validate only within ”create” context" do - doc = WithContextualValidationOnCreate.new - doc.save.should be_false - doc.name = "Alice" - doc.save.should be_true - - doc.update_attributes(:name => nil).should be_true - end - end - - describe "with contextual validation on ”update”" do - it "should validate only within ”update” context" do - doc = WithContextualValidationOnUpdate.new - doc.save.should be_true - - doc.update_attributes(:name => nil).should be_false - doc.update_attributes(:name => "Bob").should be_true - end - end - describe "save" do it "should run the after filter after saving" do @doc.run_after_save.should be_nil diff --git a/spec/unit/property_protection_spec.rb b/spec/couchrest/property_protection_spec.rb similarity index 99% rename from spec/unit/property_protection_spec.rb rename to spec/couchrest/property_protection_spec.rb index 9de0d94..eb5ca55 100644 --- a/spec/unit/property_protection_spec.rb +++ b/spec/couchrest/property_protection_spec.rb @@ -1,4 +1,4 @@ -require "spec_helper" +require File.expand_path("../../spec_helper", __FILE__) describe "Model Attributes" do diff --git a/spec/unit/property_spec.rb b/spec/couchrest/property_spec.rb similarity index 76% rename from spec/unit/property_spec.rb rename to spec/couchrest/property_spec.rb index ce4bd89..a8c81b9 100644 --- a/spec/unit/property_spec.rb +++ b/spec/couchrest/property_spec.rb @@ -1,7 +1,16 @@ # 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', 'person') +require File.join(FIXTURE_PATH, 'more', 'card') +require File.join(FIXTURE_PATH, 'more', 'invoice') +require File.join(FIXTURE_PATH, 'more', 'service') +require File.join(FIXTURE_PATH, 'more', 'event') +require File.join(FIXTURE_PATH, 'more', 'user') +require File.join(FIXTURE_PATH, 'more', 'course') -describe CouchRest::Model::Property do + +describe "Model properties" do before(:each) do reset_test_db! @@ -47,11 +56,7 @@ describe CouchRest::Model::Property do 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 + lambda { Person.property(Person.model_type_key) }.should raise_error(/already used/) end it "should be auto timestamped" do @@ -62,32 +67,6 @@ describe CouchRest::Model::Property do @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" @@ -237,16 +216,6 @@ describe CouchRest::Model::Property do 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 @@ -273,9 +242,9 @@ describe "properties of array of casted models" do 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 = { '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 @@ -292,7 +261,7 @@ describe "properties of array of casted models" do 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/) + }.should raise_error end @@ -323,28 +292,6 @@ describe "a casted model retrieved from the database" do 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 @@ -388,28 +335,6 @@ describe "Property Class" do 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 @@ -438,29 +363,14 @@ describe "Property Class" do 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)) + 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 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]) diff --git a/spec/unit/proxyable_spec.rb b/spec/couchrest/proxyable_spec.rb similarity index 80% rename from spec/unit/proxyable_spec.rb rename to spec/couchrest/proxyable_spec.rb index fd38fbc..6de3401 100644 --- a/spec/unit/proxyable_spec.rb +++ b/spec/couchrest/proxyable_spec.rb @@ -1,50 +1,25 @@ -require "spec_helper" +require File.expand_path("../../spec_helper", __FILE__) + +require File.join(FIXTURE_PATH, 'more', 'cat') class DummyProxyable < CouchRest::Model::Base - proxy_database_method :db - def db - 'db' + def proxy_database + 'db' # Do not use this! 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 "Proxyable" do describe "class methods" do + before(:each) do + @class = DummyProxyable.clone + end 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=) @@ -55,20 +30,7 @@ describe CouchRest::Model::Proxyable do 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) @@ -85,7 +47,8 @@ describe CouchRest::Model::Proxyable 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.should_receive('proxy_database').and_return('db') + @obj.should_receive(:respond_to?).with('proxy_database').and_return(true) @obj.cats end @@ -97,16 +60,26 @@ describe CouchRest::Model::Proxyable do @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.should_receive(:respond_to?).with('proxy_database').and_return(true) @obj.documents end + + it "should raise an error if the database method is missing" do + @class.proxy_for(:cats) + @obj = @class.new + @obj.should_receive(:respond_to?).with('proxy_database').and_return(false) + lambda { @obj.cats }.should raise_error(StandardError, "Missing #proxy_database method for proxy") + end + + it "should raise an error if custom database method missing" do + @class.proxy_for(:proxy_kittens, :database_method => "foobardom") + @obj = @class.new + lambda { @obj.proxy_kittens }.should raise_error(StandardError, "Missing #foobardom method for proxy") + end end end 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 @@ -134,11 +107,6 @@ describe CouchRest::Model::Proxyable 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 @@ -163,13 +131,15 @@ describe CouchRest::Model::Proxyable do end it "should proxy new call" do - @obj.should_receive(:proxy_block_update).with(:new, 'attrs', 'opts') - @obj.new('attrs', 'opts') + Cat.should_receive(:new).and_return({}) + @obj.should_receive(:proxy_update).and_return(true) + @obj.new 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') + Cat.should_receive(:build_from_database).and_return({}) + @obj.should_receive(:proxy_update).with({}).and_return(true) + @obj.build_from_database end describe "#method_missing" do @@ -309,15 +279,6 @@ describe CouchRest::Model::Proxyable do @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 @@ -355,7 +316,7 @@ describe CouchRest::Model::Proxyable do it "should allow creation of new entries" do inv = @company.proxyable_invoices.new(:client => "Lorena", :total => 35) - # inv.database.should_not be_nil + inv.database.should_not be_nil inv.save.should be_true @company.proxyable_invoices.count.should eql(1) @company.proxyable_invoices.first.client.should eql("Lorena") diff --git a/spec/unit/subclass_spec.rb b/spec/couchrest/subclass_spec.rb similarity index 89% rename from spec/unit/subclass_spec.rb rename to spec/couchrest/subclass_spec.rb index d8f835e..75ab218 100644 --- a/spec/unit/subclass_spec.rb +++ b/spec/couchrest/subclass_spec.rb @@ -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' diff --git a/spec/unit/typecast_spec.rb b/spec/couchrest/typecast_spec.rb similarity index 98% rename from spec/unit/typecast_spec.rb rename to spec/couchrest/typecast_spec.rb index 6db127e..4174001 100644 --- a/spec/unit/typecast_spec.rb +++ b/spec/couchrest/typecast_spec.rb @@ -1,5 +1,8 @@ # encoding: utf-8 -require 'spec_helper' +require File.expand_path('../../spec_helper', __FILE__) +require File.join(FIXTURE_PATH, 'more', 'cat') +require File.join(FIXTURE_PATH, 'more', 'person') +require File.join(FIXTURE_PATH, 'more', 'course') describe "Type Casting" do diff --git a/spec/unit/validations_spec.rb b/spec/couchrest/validations_spec.rb similarity index 86% rename from spec/unit/validations_spec.rb rename to spec/couchrest/validations_spec.rb index b9e2b09..f8e2f4b 100644 --- a/spec/unit/validations_spec.rb +++ b/spec/couchrest/validations_spec.rb @@ -1,6 +1,14 @@ -require "spec_helper" +require File.expand_path("../../spec_helper", __FILE__) -describe CouchRest::Model::Validations do +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 @@ -8,11 +16,7 @@ describe CouchRest::Model::Validations do before(:all) do @objs = ['title 1', 'title 2', 'title 3'].map{|t| WithUniqueValidation.create(:title => t)} end - - it "should create a new view if none defined before performing" do - WithUniqueValidation.has_view?(:by_title).should be_true - end - + it "should validate a new unique document" do @obj = WithUniqueValidation.create(:title => 'title 4') @obj.new?.should_not be_true @@ -31,7 +35,6 @@ describe CouchRest::Model::Validations do @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') @@ -47,13 +50,6 @@ describe CouchRest::Model::Validations do }.should raise_error end - it "should not try to create a defined view" do - WithUniqueValidationView.validates_uniqueness_of :title, :view => 'fooobar' - WithUniqueValidationView.has_view?('fooobar').should be_false - WithUniqueValidationView.has_view?('by_title').should be_false - end - - it "should not try to create new view when already defined" do @obj = @objs[1] @obj.class.should_not_receive('view_by') @@ -64,11 +60,6 @@ describe CouchRest::Model::Validations do end context "with a proxy parameter" do - - it "should create a new view despite proxy" do - WithUniqueValidationProxy.has_view?(:by_title).should be_true - end - it "should be used" do @obj = WithUniqueValidationProxy.new(:title => 'test 6') proxy = @obj.should_receive('proxy').and_return(@obj.class) diff --git a/spec/unit/view_spec.rb b/spec/couchrest/view_spec.rb similarity index 93% rename from spec/unit/view_spec.rb rename to spec/couchrest/view_spec.rb index d69630c..e9259ff 100644 --- a/spec/unit/view_spec.rb +++ b/spec/couchrest/view_spec.rb @@ -1,18 +1,19 @@ -require "spec_helper" +require File.expand_path("../../spec_helper", __FILE__) +require File.join(FIXTURE_PATH, 'more', 'cat') +require File.join(FIXTURE_PATH, 'more', 'person') +require File.join(FIXTURE_PATH, 'more', 'article') +require File.join(FIXTURE_PATH, 'more', 'course') -describe CouchRest::Model::Views do +describe "Model views" do class Unattached < CouchRest::Model::Base + # 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! @@ -173,22 +174,7 @@ describe CouchRest::Model::Views do end end - - describe "#method_missing for find_by methods" do - before(:all) { reset_test_db! } - - specify { Course.should respond_to :find_by_title_and_active } - specify { Course.should respond_to :by_title } - - specify "#method should work in ruby 1.9, but not 1.8" do - if RUBY_VERSION >= "1.9" - Course.method(:find_by_title_and_active).should be_a Method - else - expect { Course.method(:find_by_title_and_active) }.to raise_error(NameError) - end - end - end - + describe "a ducktype view" do before(:all) do reset_test_db! @@ -209,7 +195,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 diff --git a/spec/fixtures/models/base.rb b/spec/fixtures/base.rb similarity index 86% rename from spec/fixtures/models/base.rb rename to spec/fixtures/base.rb index 8e62eb8..d395b4a 100644 --- a/spec/fixtures/models/base.rb +++ b/spec/fixtures/base.rb @@ -83,32 +83,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 +107,7 @@ end class WithAfterInitializeMethod < CouchRest::Model::Base use_database TEST_SERVER.default_database - + property :some_value def after_initialize diff --git a/spec/fixtures/config/couchdb.yml b/spec/fixtures/config/couchdb.yml deleted file mode 100644 index 8d04ff7..0000000 --- a/spec/fixtures/config/couchdb.yml +++ /dev/null @@ -1,10 +0,0 @@ - -development: - protocol: 'https' - host: sample.cloudant.com - port: 443 - prefix: project - suffix: text - username: test - password: user - diff --git a/spec/fixtures/models/key_chain.rb b/spec/fixtures/models/key_chain.rb deleted file mode 100644 index 0837e39..0000000 --- a/spec/fixtures/models/key_chain.rb +++ /dev/null @@ -1,5 +0,0 @@ -class KeyChain < CouchRest::Model::Base - use_database(DB) - - property(:keys, Hash) -end diff --git a/spec/fixtures/models/membership.rb b/spec/fixtures/models/membership.rb deleted file mode 100644 index 81c804e..0000000 --- a/spec/fixtures/models/membership.rb +++ /dev/null @@ -1,4 +0,0 @@ -class Membership - include CouchRest::Model::Embeddable - -end diff --git a/spec/fixtures/models/project.rb b/spec/fixtures/models/project.rb deleted file mode 100644 index d8de244..0000000 --- a/spec/fixtures/models/project.rb +++ /dev/null @@ -1,6 +0,0 @@ -class Project < CouchRest::Model::Base - use_database DB - property :name, String - timestamps! - view_by :name -end diff --git a/spec/fixtures/models/question.rb b/spec/fixtures/models/question.rb deleted file mode 100644 index ada5bd9..0000000 --- a/spec/fixtures/models/question.rb +++ /dev/null @@ -1,7 +0,0 @@ -class Question - include ::CouchRest::Model::Embeddable - - property :q - property :a - -end diff --git a/spec/fixtures/models/article.rb b/spec/fixtures/more/article.rb similarity index 97% rename from spec/fixtures/models/article.rb rename to spec/fixtures/more/article.rb index 6e2af99..9e370e3 100644 --- a/spec/fixtures/models/article.rb +++ b/spec/fixtures/more/article.rb @@ -22,7 +22,6 @@ class Article < CouchRest::Model::Base property :date, Date property :slug, :read_only => true - property :user_id property :title property :tags, [String] diff --git a/spec/fixtures/models/card.rb b/spec/fixtures/more/card.rb similarity index 95% rename from spec/fixtures/models/card.rb rename to spec/fixtures/more/card.rb index 8cf72ab..7494b44 100644 --- a/spec/fixtures/models/card.rb +++ b/spec/fixtures/more/card.rb @@ -1,5 +1,3 @@ -require 'person' - class Card < CouchRest::Model::Base # Set the default database to use use_database DB diff --git a/spec/fixtures/models/cat.rb b/spec/fixtures/more/cat.rb similarity index 71% rename from spec/fixtures/models/cat.rb rename to spec/fixtures/more/cat.rb index a28f505..903eafd 100644 --- a/spec/fixtures/models/cat.rb +++ b/spec/fixtures/more/cat.rb @@ -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 diff --git a/spec/fixtures/models/client.rb b/spec/fixtures/more/client.rb similarity index 100% rename from spec/fixtures/models/client.rb rename to spec/fixtures/more/client.rb diff --git a/spec/fixtures/models/course.rb b/spec/fixtures/more/course.rb similarity index 88% rename from spec/fixtures/models/course.rb rename to spec/fixtures/more/course.rb index 2998bb2..d06f6a0 100644 --- a/spec/fixtures/models/course.rb +++ b/spec/fixtures/more/course.rb @@ -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 diff --git a/spec/fixtures/models/event.rb b/spec/fixtures/more/event.rb similarity index 100% rename from spec/fixtures/models/event.rb rename to spec/fixtures/more/event.rb diff --git a/spec/fixtures/models/invoice.rb b/spec/fixtures/more/invoice.rb similarity index 98% rename from spec/fixtures/models/invoice.rb rename to spec/fixtures/more/invoice.rb index 927fd8f..540c9ff 100644 --- a/spec/fixtures/models/invoice.rb +++ b/spec/fixtures/more/invoice.rb @@ -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 diff --git a/spec/fixtures/models/person.rb b/spec/fixtures/more/person.rb similarity index 56% rename from spec/fixtures/models/person.rb rename to spec/fixtures/more/person.rb index 71525e4..076bbc0 100644 --- a/spec/fixtures/models/person.rb +++ b/spec/fixtures/more/person.rb @@ -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] diff --git a/spec/fixtures/more/question.rb b/spec/fixtures/more/question.rb new file mode 100644 index 0000000..5efcd20 --- /dev/null +++ b/spec/fixtures/more/question.rb @@ -0,0 +1,7 @@ +class Question < Hash + include ::CouchRest::Model::CastedModel + + property :q + property :a + +end diff --git a/spec/fixtures/models/sale_entry.rb b/spec/fixtures/more/sale_entry.rb similarity index 100% rename from spec/fixtures/models/sale_entry.rb rename to spec/fixtures/more/sale_entry.rb diff --git a/spec/fixtures/models/sale_invoice.rb b/spec/fixtures/more/sale_invoice.rb similarity index 60% rename from spec/fixtures/models/sale_invoice.rb rename to spec/fixtures/more/sale_invoice.rb index 5244ba5..ad6beb2 100644 --- a/spec/fixtures/models/sale_invoice.rb +++ b/spec/fixtures/more/sale_invoice.rb @@ -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 \ No newline at end of file diff --git a/spec/fixtures/models/service.rb b/spec/fixtures/more/service.rb similarity index 100% rename from spec/fixtures/models/service.rb rename to spec/fixtures/more/service.rb diff --git a/spec/fixtures/models/user.rb b/spec/fixtures/more/user.rb similarity index 100% rename from spec/fixtures/models/user.rb rename to spec/fixtures/more/user.rb diff --git a/spec/functional/validations_spec.rb b/spec/functional/validations_spec.rb deleted file mode 100644 index fc06203..0000000 --- a/spec/functional/validations_spec.rb +++ /dev/null @@ -1,8 +0,0 @@ -require File.expand_path('../../spec_helper', __FILE__) - -describe CouchRest::Model::Validations do - - let(:invoice) do - Invoice.new() - end -end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index d04b99f..75ed89d 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,16 +1,11 @@ -$LOAD_PATH.unshift(File.dirname(__FILE__)) -$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "lib")) - require "bundler/setup" require "rubygems" -require "rspec" +require "rspec" # Satisfies Autotest and anyone else not using the Rake tasks -require 'couchrest_model' +require File.join(File.dirname(__FILE__), '..','lib','couchrest_model') +# check the following file to see how to use the spec'd features. unless defined?(FIXTURE_PATH) - 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') @@ -21,21 +16,6 @@ unless defined?(FIXTURE_PATH) DB = TEST_SERVER.database(TESTDB) end -RSpec.configure do |config| - config.before(:all) { reset_test_db! } - - config.after(:all) do - cr = TEST_SERVER - test_dbs = cr.databases.select { |db| db =~ /^#{TESTDB}/ } - test_dbs.each do |db| - cr.database(db).delete! rescue nil - end - end -end - -# Require each of the fixture models -Dir[ File.join(MODEL_PATH, "*.rb") ].sort.each { |file| require File.basename(file) } - class Basic < CouchRest::Model::Base use_database TEST_SERVER.default_database end @@ -47,6 +27,17 @@ def reset_test_db! DB end +RSpec.configure do |config| + config.before(:all) { reset_test_db! } + + config.after(:all) do + cr = TEST_SERVER + test_dbs = cr.databases.select { |db| db =~ /^#{TESTDB}/ } + test_dbs.each do |db| + cr.database(db).delete! rescue nil + end + end +end def couchdb_lucene_available? lucene_path = "http://localhost:5985/" diff --git a/spec/unit/active_model_lint_spec.rb b/spec/unit/active_model_lint_spec.rb deleted file mode 100644 index 3cc5d3d..0000000 --- a/spec/unit/active_model_lint_spec.rb +++ /dev/null @@ -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 diff --git a/spec/unit/connection_spec.rb b/spec/unit/connection_spec.rb deleted file mode 100644 index 4607991..0000000 --- a/spec/unit/connection_spec.rb +++ /dev/null @@ -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 diff --git a/spec/unit/inherited_spec.rb b/spec/unit/inherited_spec.rb deleted file mode 100644 index 04b8e3d..0000000 --- a/spec/unit/inherited_spec.rb +++ /dev/null @@ -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 - -