Class: JohnDoe::Responser

Inherits:
Object
  • Object
show all
Defined in:
lib/johndoe/responser.rb

Instance Method Summary collapse

Constructor Details

#initialize(data, quotes) ⇒ Responser

Returns a new instance of Responser.



10
11
12
13
14
15
# File 'lib/johndoe/responser.rb', line 10

def initialize(data, quotes)
  @data = data
  @markov = Markov.new
  @markov.load quotes
  @quotes_file = File.open(quotes,"a")
end

Instance Method Details

#describe_who(s) ⇒ Object



63
64
65
66
# File 'lib/johndoe/responser.rb', line 63

def describe_who(s)
  s = s.gsub(/([^a-z])am\s+i([^a-z]|$)/,"\\1#AMI#\\2").gsub(/([^a-z])i\s+am([^a-z]|$)/,"\\1#IAM#\\2").gsub(/([^a-z])you\s+are([^a-z]|$)/,"\\1#AREYOU#\\2").gsub(/([^a-z])are\s+you([^a-z]|$)/,"\\1#AREYOU#\\2").gsub(/([^a-z])me([^a-z]|$)/,"\\1#ME#\\2").gsub(/([^a-z])you([^a-z]|$)/,"\\1#YOU#\\2").gsub(/([^a-z])your([^a-z]|$)/,"\\1#YOUR#\\2").gsub(/([^a-z])my([^a-z]|$)/,"\\1#MY#\\2")
  s.gsub("#AMI#","you are").gsub("#IAM#","you are").gsub("#AREYOU#","I am").gsub("#ME#","you").gsub("#YOU#","me").gsub("#YOUR#","my").gsub("#MY#","your")
end

#get_data(path) ⇒ Object

get_data bot:name



48
49
50
51
52
# File 'lib/johndoe/responser.rb', line 48

def get_data(path)
  root = @data.knowledge
  path.split(":").each {|v|root = root[v]}
  return root
end

#random_quote(s, subjects = []) ⇒ Object



54
55
56
# File 'lib/johndoe/responser.rb', line 54

def random_quote(s, subjects = [])
  return subject_replace(s[rand(s.size)], subjects)
end

#response(sentence) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/johndoe/responser.rb', line 17

def response(sentence)
  max_priority = -1
  best_v = nil
  best_k = nil

  @data.patterns.each do |k,v|
    if (/^#{k}/i =~ sentence)
      next if v[:priority] <= max_priority
      max_priority = v[:priority]
      best_v = v
      best_k = k
    end
  end
  unless best_v.nil?
    return Response.new(sub_v(random_quote(@data.responses[best_v[:resp]], /^#{best_k}/i.match(sentence).captures)),best_v[:emotions])
  else
    generated = @markov.response sentence
    return Response.new(generated, ["none"]) unless generated.nil?
    return Response.new(sub_v(random_quote(@data.default["dontunderstand"])),["none"])
  end
end

#sub_v(s) ⇒ Object

substitute variables



40
41
42
43
44
45
# File 'lib/johndoe/responser.rb', line 40

def sub_v(s)
  while (nil != (match = /(([a-z]+:)([a-z]+)+)/.match s))
    s.gsub!(match[0],get_data(match[0]))
  end
  return s
end

#subject_replace(s, subjects = []) ⇒ Object



58
59
60
61
# File 'lib/johndoe/responser.rb', line 58

def subject_replace(s,subjects = [])
  return s if subjects.empty?
  return s.gsub("$",describe_who(subjects[0]))
end