As part of my couchrest refactoring required for assay-depot (client),
I implemented the new Rails3 callback systems in CR.
Here is an example of a CouchRest::ExtendedDocument class using
validation
class Card < CouchRest::ExtendedDocument
# Include the validation module to get access to the validation
methods
include CouchRest::Validation
# Set the default database to use
use_database TEST_SERVER.default_database
# Official Schema
property :first_name
property :last_name, :alias => :family_name
property :read_only_value, :read_only => true
timestamps!
# Validation
validates_present :first_name
end
Validation uses a before filter to validate your objects.
If you look at lib/more/extended_document.rb you will notice that we
have 2 callbacks defined by default:
define_callbacks :save
define_callbacks :destroy
You can use one of these callbacks easily as shown below:
save_callback :before, :log_stuff
Here is the implementation of #save in ExtendedDocument
# Trigger the callbacks (before, after, around)
# and save the document
def save(bulk = false)
caught = catch(:halt) do
_run_save_callbacks do
save_without_callbacks(bulk)
end
end
end
If you want to make a filter halt, just do: throw(:halt)
In the case of above save method, it makes sense to throw(:halt,
false) so if the a fails save will be false.
When you include CouchRest::Validation to a class, the following code
is evaluated:
if (method_defined?(:save) && method_defined?
(:_run_save_callbacks))
save_callback :before, :check_validations
end
def check_validations(context = :default)
throw(:halt, false) unless context.nil? || valid?(context)
end
You might wonder about the contexts, well... it's not fully
implemented, so let's talk about that later ;)
I know Chris wanted to get rid of the Extlib dependency so I'm glad to
say that we potentially don't need Extlib hooking system as we have a
better one available in CR :)
Before I forget, if you want to use the callback system on a non CR
class, just include CouchRest::Callbacks, 100% pain free :)
- Matt
http://github.com/mattetti/couchrest/commit/fec21c3ff326d94f884ef3ac18bbdbd875a56492