Sha256: 5ab740881b94e7b2f2f61ab090d8b0f0ffe90ec06aea9301433a5a1d26eaa55d

Contents?: true

Size: 1.26 KB

Versions: 2

Compression:

Stored size: 1.26 KB

Contents

require "attentive/text"
require "attentive/tokenizer"
require "set"

module Attentive
  class Listener
    attr_reader :phrases

    def initialize(listeners, phrases, options, callback)
      context_options = options.fetch(:context, {})
      @required_contexts = context_options.fetch(:in, %i{conversation})
      @required_contexts = [] if @required_contexts == :any
      @required_contexts = Set[*@required_contexts]
      @prohibited_contexts = context_options.fetch(:not_in, %i{quotation})
      @prohibited_contexts = Set[*@prohibited_contexts]

      @listeners = listeners
      @phrases = tokenize_phrases!(phrases)
      @callback = callback
    end

    def matches_context?(message)
      return false unless message.contexts.superset? @required_contexts
      return false unless message.contexts.disjoint? @prohibited_contexts
      true
    end

    def stop_listening!
      listeners.delete self
      self
    end

    def call(e)
      @callback.call(e)
    end

  private
    attr_reader :listeners

    def tokenize_phrases!(phrases)
      phrases.map do |phrase|
        tokenize_phrase!(phrase)
      end
    end

    def tokenize_phrase!(phrase)
      Attentive::Tokenizer.tokenize(phrase, entities: true, regexps: true, ambiguous: false)
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
attentive-0.1.1 lib/attentive/listener.rb
attentive-0.1.0 lib/attentive/listener.rb