Radagaisus/Orpheus — pull request #7 by Radagaisus (2014-08-18 01:07:58+00:00)
Title: conditional when

```
# 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
```

```
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()
```