From 011dd67008a3465dfb48918649a41bb5bef32503 Mon Sep 17 00:00:00 2001 From: Radagaisus Date: Mon, 18 Aug 2014 04:07:00 +0300 Subject: [PATCH] conditional when --- lib/orpheus.coffee | 33 +++++++++++++++++++++++++++++---- test/orpheus.spec.coffee | 31 ++++++++++++++++++++++++++++++- 2 files changed, 59 insertions(+), 5 deletions(-) diff --git a/lib/orpheus.coffee b/lib/orpheus.coffee index 600c16d..bcd264a 100644 --- a/lib/orpheus.coffee +++ b/lib/orpheus.coffee @@ -372,12 +372,37 @@ class OrpheusAPI # New or existing id @id = id or @_generate_id() - # If and Unless are used to discard changes - # unless certain conditions are met - @only = @when = (fn) => - fn.bind(this)() + + # Runs the given `function` inside the model context. Optionally, if `only` + # or `when` receive the `condition` parameter it will only run the function + # conditionally. + # + # Example usage: + # + # User('john') + # .when -> + # if the_sky_is_blue then @name.set('happy john') + # .exec() + # + # User('john') + # .when the_sky_is_blue, -> + # @name.set('happy john') + # .exec() + # + # @param condition - {Mixed} if just one argument is passed, `condition` is + # assumed to be the function to run in the context of the model. If two arguments + # are passed, `condition` will be used to evaluate whether to run the function or + # not. + # @param fn - {Function} the function to run in the context of the model + # @return {this} for chaining + # + @only = @when = (condition, fn = condition) => + # Apply the function in the current context if the condition is truthy + fn.bind(this)() if condition + # Return `this` for chaining return this + # Create functions for working with the relation set # e.g. user(15).books.sadd('dune') will map to sadd # orpheus:us:15:books dune. diff --git a/test/orpheus.spec.coffee b/test/orpheus.spec.coffee index ce0ad33..5cab670 100644 --- a/test/orpheus.spec.coffee +++ b/test/orpheus.spec.coffee @@ -308,7 +308,8 @@ describe 'Redis Commands', -> .name.set('greg') .exec() - it 'When', (done) -> + it '#When', (done) -> + class Player extends Orpheus constructor: -> @str 'name' @@ -332,6 +333,34 @@ describe 'Redis Commands', -> expect(res[0]).toBe 1 done() + it '#When with a condition as parameter', (done) -> + + class User extends Orpheus + constructor: -> + @str 'name' + + user = User.create() + + user('test') + .name.set('hi') + .when true, -> @name.set('hello') + .exec -> + r.hget "#{PREFIX}:us:test", 'name', (_, res) -> + expect(res).toBe 'hello' + + user('test2') + .name.set('hi') + .when false, -> + # I have no idea why, but moving this to the same line as the `when` + # will make the tests hang. BUT, it does work if the condition is true. + @name.set('hello') + .exec -> + + r.hget "#{PREFIX}:us:test2", 'name', (_, res) -> + expect(res).toBe 'hi' + + done() + # Getting Stuff # ----------------------------------------------