Skip to content

Instantly share code, notes, and snippets.

@sweetpi
Last active August 29, 2015 14:01
Show Gist options
  • Save sweetpi/11f7ce564b5ab842ba05 to your computer and use it in GitHub Desktop.
Save sweetpi/11f7ce564b5ab842ba05 to your computer and use it in GitHub Desktop.
predicate-handler
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
)
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
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