Skip to content

Commit

Permalink
fix(BaseEntity): Pass the entity to when closures
Browse files Browse the repository at this point in the history
To enable calling scopes and other Quick methods,
the BaseEntity now has its own version of `when`
that it uses to pass the entity on instead of just
the QueryBuilder instance.
  • Loading branch information
elpete committed Dec 9, 2019
1 parent a2e0bc3 commit 96a8f3a
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
28 changes: 28 additions & 0 deletions models/BaseEntity.cfc
Original file line number Diff line number Diff line change
Expand Up @@ -1011,6 +1011,34 @@ component accessors="true" {
return this;
}

/**
* This method mirrors qb's `when` method.
* It exists so we can pass through the entity
* to the closures instead of just the QueryBuilder.
*
* @condition A boolean condition that if true will trigger the `onTrue` callback.
* If not true the `onFalse` callback will trigger, if it was passed.
* Otherwise, the query is returned unmodified.
* @onTrue A closure that will be triggered if the `condition` is true.
* @onFalse A closure that will be triggered if the `condition` is false.
*/
public function when(
required boolean condition,
onTrue,
onFalse
) {
var defaultCallback = function( q ) {
return q;
};
onFalse = isNull( onFalse ) ? defaultCallback : onFalse;
if ( condition ) {
onTrue( this );
} else {
onFalse( this );
}
return this;
}

function newCollection( array entities = [] ) {
return arguments.entities;
}
Expand Down
6 changes: 6 additions & 0 deletions tests/resources/app/models/User.cfc
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ component quick {
return query.where( "type", type );
}

function scopeOfTypeWithWhen( query, type ) {
return query.when( ! isNull( type ) && len( type ), function( q ) {
q.ofType( type );
} );
}

function scopeResetPasswords( query ) {
return query.updateAll( { "password" = "" } ).result.recordcount;
}
Expand Down
6 changes: 6 additions & 0 deletions tests/specs/integration/BaseEntity/ScopeSpec.cfc
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ component extends="tests.resources.ModuleIntegrationSpec" appMapping="/app" {
it( "can return values from scopes as well as instances", function() {
expect( getInstance( "User" ).ofType( "admin" ).resetPasswords() ).toBe( 1 );
} );

it( "can use the qb `when` helper in scopes", function() {
var users = getInstance( "User" ).ofTypeWithWhen( "admin" ).get();
expect( users ).toHaveLength( 1, "One user should exist in the database and be returned." );
expect( users[ 1 ].getUsername() ).toBe( "elpete" );
} );
} );
}

Expand Down

0 comments on commit 96a8f3a

Please sign in to comment.