Skip to content

Commit

Permalink
conditional when
Browse files Browse the repository at this point in the history
  • Loading branch information
Radagaisus committed Aug 18, 2014
1 parent e238781 commit 011dd67
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 5 deletions.
33 changes: 29 additions & 4 deletions lib/orpheus.coffee
Expand Up @@ -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.
Expand Down
31 changes: 30 additions & 1 deletion test/orpheus.spec.coffee
Expand Up @@ -308,7 +308,8 @@ describe 'Redis Commands', ->
.name.set('greg')
.exec()

it 'When', (done) ->
it '#When', (done) ->

class Player extends Orpheus
constructor: ->
@str 'name'
Expand All @@ -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
# ----------------------------------------------
Expand Down

0 comments on commit 011dd67

Please sign in to comment.