Last active
August 29, 2015 14:01
-
-
Save sweetpi/11f7ce564b5ab842ba05 to your computer and use it in GitHub Desktop.
predicate-handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AnswerPredicateHandler extends PredicateHandler | |
constructor: (@framework, @leftTokens) -> | |
setup: -> | |
@lastState = null | |
@variables = @framework.variableManager.extractVariables(@leftTokens) | |
@changeListener = () => | |
@_evaluate().then( (state) => | |
if state isnt @lastState | |
@lastState = state | |
@emit 'change', state | |
).catch( (error) => | |
env.logger.error "Error in AnswerPredicateHandler:", error.message | |
env.logger.debug error | |
) | |
for v in @variables | |
@framework.variableManager.on("change #{v}", @changeListener) | |
super() | |
getValue: -> | |
if @lastState? then return Q(@lastState) | |
else return @_evaluate() | |
destroy: -> | |
for v in @variables | |
@framework.variableManager.removeListener("change #{v}", @changeListener) | |
super() | |
getType: -> 'state' | |
# private helper | |
_evaluate: -> | |
@framework.variableManager.evaluateNumericExpression(@leftTokens).then( (val) => | |
return val is 42 | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AnswerPredicateProvider extends PredicateProvider | |
constructor: (@framework) -> | |
parsePredicate: (input, context) -> | |
result = null | |
allVariables = _(@framework.variableManager.getAllVariables()).map( (v) => v.name ).valueOf() | |
M(input, context) | |
.matchNumericExpression(allVariables, (next, leftTokens) => | |
next.match(' is 42', (next) => | |
result = { | |
leftTokens | |
match: next.getFullMatch() | |
} | |
) | |
) | |
if result? | |
assert Array.isArray result.leftTokens | |
return { | |
token: result.match | |
nextInput: input.substring(result.match.length) | |
predicateHandler: new VariablePredicateHandler( | |
@framework, | |
result.leftTokens | |
) | |
} | |
else | |
return null |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class YourPlugin extends env.plugins.Plugin | |
init: (app, @framework, config) => | |
# [...] | |
@framework.ruleManager.addPredicateProvider(new AnswerPredicateProvider(@framework)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment