couchrest_model/README.md

368 lines
12 KiB
Markdown
Raw Normal View History

# CouchRest Model: CouchDB, close to shiny metal with rounded edges
2008-09-07 21:54:22 +02:00
CouchRest Models adds additional functionality to the standard CouchRest Document class such as
setting properties, callbacks, typecasting, and validations.
2008-09-07 21:54:22 +02:00
Originally called ExtendedDocument, the new Model structure uses ActiveModel, part of Rails 3,
for validations and callbacks.
If your project is still running Rails 2.3, you'll have to continue using ExtendedDocument as
it is not possible to load ActiveModel into programs that do not use ActiveSupport 3.0.
CouchRest Model only supports CouchDB 0.10.0 or newer.
2008-09-07 21:54:22 +02:00
## Install
2009-04-16 21:20:17 +02:00
### From Gem
CouchRest Model depends on Rails 3's ActiveModel which has not yet been released. You'll need to add
`--pre` to the end of the gem install until the dependencies are stable:
$ sudo gem install couchrest_model --pre
### Bundler
If you're using bundler, just define a line similar to the following in your project's Gemfile:
gem 'couchrest_model'
You might also consider using the latest git repository. All tests should pass in the master code branch
but no guarantees!
gem 'couchrest_model', :git => 'git://github.com/couchrest/couchrest_model.git'
2010-08-24 01:27:17 +02:00
## Generators
### Model
$ rails generate model person --orm=couchrest_model
## General Usage
require 'couchrest_model'
class Cat < CouchRest::Model::Base
2010-06-11 02:02:22 +02:00
property :name, String
property :lives, Integer, :default => 9
property :nicknames, [String]
timestamps!
view_by :name
2008-09-07 21:54:22 +02:00
end
2008-09-07 21:54:22 +02:00
2010-06-16 21:04:53 +02:00
@cat = Cat.new(:name => 'Felix', :nicknames => ['so cute', 'sweet kitty'])
@cat.new? # true
@cat.save
@cat['name'] # "Felix"
@cat.nicknames << 'getoffdamntable'
@cat = Cat.new
@cat.update_attributes(:name => 'Felix', :random_text => 'feline')
@cat.new? # false
@cat.random_text # Raises error!
## Properties
2010-06-16 21:04:53 +02:00
A property is the definition of an attribute, it describes what the attribute is called, how it should
be type casted, if at all, and other options such as the default value. These replace your typical
`add_column` methods typically found in migrations.
2010-06-16 21:04:53 +02:00
By default only attributes with a property definition will be stored in CouchRest Model, as opposed
to a normal CouchRest Document which will store everything. This however can be disabled using the
`allow_dynamic_properties` configuration option either for all of CouchRest Model, or for specific
models. See the configuration section for more details.
2010-06-16 21:04:53 +02:00
In its simplest form, a property
will only create a getter and setter passing all attribute data directly to the database. Assuming the attribute
2010-07-02 00:56:26 +02:00
provided responds to `to_json`, there will not be any problems saving it, but when loading the
2010-06-16 21:04:53 +02:00
data back it will either be a string, number, array, or hash:
class Cat < CouchRest::Model::Base
2010-06-16 21:04:53 +02:00
property :name
property :birthday
end
@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
2010-06-16 21:04:53 +02:00
property :name, String
property :last_fed_at, Time
end
@cat = Cat.new(:name => 'Felix', :last_fed_at => 10.minutes.ago)
@cat.last_fed_at.is_a?(Time) # True!
@cat.save
@cat = Cat.find(@cat.id)
@cat.last_fed_at < 20.minutes.ago # True!
Booleans or TrueClass will also create a getter with question mark at the end:
class Cat < CouchRest::Model::Base
2010-06-16 21:04:53 +02:00
property :awake, TrueClass, :default => true
end
@cat.awake? # true
Adding the +:default+ option will ensure the attribute always has a value.
Defining a property as read-only will mean that its value is set only when read from the
database and that it will not have a setter method. You can however update a read-only
2010-07-02 00:56:26 +02:00
attribute using the `write_attribute` method:
2010-06-16 21:04:53 +02:00
class Cat < CouchRest::Model::Base
2010-06-16 21:04:53 +02:00
property :name, String
property :lives, Integer, :default => 9, :readonly => true
def fall_off_balcony!
write_attribute(:lives, lives - 1)
save
end
end
@cat = Cat.new(:name => "Felix")
@cat.fall_off_balcony!
@cat.lives # Now 8!
## Property Arrays
2010-06-16 21:04:53 +02:00
An attribute may also contain an array of data. CouchRest Model handles this, along
2010-06-16 21:04:53 +02:00
with casting, by defining the class of the child attributes inside an Array:
class Cat < CouchRest::Model::Base
2010-06-16 21:04:53 +02:00
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
2010-07-02 00:56:26 +02:00
into special wrapper called a CastedArray. If the child objects respond to the `casted_by` method
2010-06-16 21:04:53 +02:00
(such as those created with CastedModel, below) it will contain a reference to the parent.
## Casted Models
2010-06-16 21:04:53 +02:00
CouchRest Model allows you to take full advantage of CouchDB's ability to store complex
2010-06-16 21:04:53 +02:00
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
2010-06-16 21:04:53 +02:00
property :name, String
property :purchased, Date
end
class Cat << CouchRest::Model::Base
2010-06-16 21:04:53 +02:00
property :name, String
property :toys, [CatToy]
end
@cat = Cat.new(:name => 'Felix', :toys => [{:name => 'mouse', :purchases => 1.month.ago}])
@cat.toys.first.class == CatToy
@cat.toys.first.name == 'mouse'
Additionally, any hashes sent to the property will automatically be converted:
@cat.toys << {:name => 'catnip ball'}
@cat.toys.last.is_a?(CatToy) # True!
Of course, to use your own classes they *must* be defined before the parent uses them otherwise
Ruby will bring up a missing constant error. To avoid this, or if you have a really simple array of data
you'd like to model, the latest version of CouchRest Model (> 1.0.0) supports creating
2010-06-16 21:04:53 +02:00
anonymous classes:
class Cat << CouchRest::Model::Base
2010-06-16 21:04:53 +02:00
property :name, String
property :toys do |toy|
toy.property :name, String
toy.property :rating, Integer
end
end
@cat = Cat.new(:name => 'Felix', :toys => [{:name => 'mouse', :rating => 3}, {:name => 'catnip ball', :rating => 5}])
@cat.toys.last.rating == 5
@cat.toys.last.name == 'catnip ball'
Using this method of anonymous classes will *only* create arrays of objects.
## Assocations
Two types at the moment:
belongs_to :person
collection_of :tags
TODO: Document properly!
## Validations
CouchRest Model automatically includes the new ActiveModel validations, so they should work just as the traditional Rails
validations. For more details, please see the ActiveModel::Validations documentation.
2010-07-02 00:56:26 +02:00
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
2010-07-02 00:56:26 +02:00
specify a different view using the `:view` option, useful for when the `unique_id` is specified and
you'd like to avoid the typical RestClient Conflict error:
unique_id :code
validates_uniqueness_of :code, :view => 'all'
Given that the uniqueness check performs a request to the database, it is also possible
to include a @:proxy@ parameter. This allows you to
call a method on the document and provide an alternate proxy object.
Examples:
# Same as not including proxy:
validates_uniqueness_of :title, :proxy => 'class'
# Person#company.people provides a proxy object for people
validates_uniqueness_of :title, :proxy => 'company.people'
A really interesting use of +:proxy+ and +:view+ together could be where
you'd like to ensure the ID is unique between several types of document. For example:
class Product < CouchRest::Model::Base
property :code
validates_uniqueness_of :code, :view => 'by_product_code'
view_by :product_code, :map => "
function(doc) {
if (doc['couchrest-type'] == 'Product' || doc['couchrest-type'] == 'Project') {
emit(doc['code']);
}
}
"
end
class Project < CouchRest::Model::Base
property :code
validates_uniqueness_of :code, :view => 'by_product_code', :proxy => 'Product'
end
Pretty cool!
## Configuration
CouchRest Model supports a few configuration options. These can be set either for the whole Model code
base or for a specific model of your chosing. To configure globally, provide something similar to the
following in your projects loading code:
CouchRestModel::Model::Base.configure do |config|
config.allow_dynamic_properties = true
config.model_type_key = 'couchrest-type'
end
To set for a specific model:
class Cat < CouchRest::Model::Base
allow_dynamic_properties true
end
Options currently avilable are:
* `allow_dynamic_properties` - false by default, when true properties do not need to be defined to be stored, although they will have no accessors.
* `model_type_key` - 'model' by default, useful for migrating from an older CouchRest ExtendedDocument when the default used to be 'couchrest-type'.
## Notable Issues
2010-06-16 12:40:00 +02:00
CouchRest Model uses active_support for some of its internals. Ensure you have a stable active support gem installed
2010-06-16 12:40:00 +02:00
or at least 3.0.0.beta4.
JSON gem versions 1.4.X are kown to cause problems with stack overflows and general badness. Version 1.2.4 appears to work fine.
## Ruby on Rails
CouchRest Model is compatible with rails and provides some ActiveRecord-like methods.
2010-06-11 02:02:22 +02:00
The CouchRest companion rails project
[http://github.com/hpoydar/couchrest-rails](http://github.com/hpoydar/couchrest-rails) is great
for provided default connection details for your database. At the time of writting however it
does not provide explicit support for CouchRest Model.
2010-06-11 02:02:22 +02:00
CouchRest Model and the original CouchRest ExtendedDocument do not share the same namespace,
as such you should not have any problems using them both at the same time. This might
help with migrations.
### Rails 3.0
2010-06-21 23:56:42 +02:00
In your Gemfile require the gem with a simple line:
gem "couchrest_model"
## Testing
2008-09-07 21:54:22 +02:00
2008-10-02 19:57:13 +02:00
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).
2008-09-07 21:54:22 +02:00
2010-01-14 02:16:16 +01:00
## Docs
API: [http://rdoc.info/projects/couchrest/couchrest_model](http://rdoc.info/projects/couchrest/couchrest_model)
2010-07-29 02:38:50 +02:00
Check the wiki for documentation and examples [http://wiki.github.com/couchrest/couchrest_model](http://wiki.github.com/couchrest/couchrest_model)
2010-01-14 01:56:21 +01:00
2010-06-11 02:02:22 +02:00
2010-01-14 02:16:16 +01:00
## Contact
2010-01-14 01:56:21 +01:00
2010-07-29 02:40:19 +02:00
Please post bugs, suggestions and patches to the bug tracker at [http://github.com/couchrest/couchrest_model/issues](http://github.com/couchrest/couchrest_model/issues).
2010-01-14 01:56:21 +01:00
2010-03-31 02:38:26 +02:00
Follow us on Twitter: [http://twitter.com/couchrest](http://twitter.com/couchrest)
2010-01-14 01:56:21 +01:00
2010-03-31 02:38:26 +02:00
Also, check [http://twitter.com/#search?q=%23couchrest](http://twitter.com/#search?q=%23couchrest)
2009-07-17 20:07:23 +02:00