Class: Brane

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

Constant Summary collapse

VERSION =
"0.0.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path = "brane.tcb") ⇒ Brane

Returns a new instance of Brane.



7
8
9
10
# File 'lib/brane.rb', line 7

def initialize(path = "brane.tcb")
  path = File.expand_path(path.sub(/\.[^\.]*$/, ".tcb"))
  @db = OklahomaMixer.open(path)
end

Instance Attribute Details

#dbObject (readonly)

Returns the value of attribute db.



5
6
7
# File 'lib/brane.rb', line 5

def db
  @db
end

Instance Method Details

#add(text) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/brane.rb', line 12

def add(text)
  text.split(/\b[!?\.]+\s*/).each do |sentence|
    sentence.split(/\s+/).map do |word|
      normalize_word(word)
    end.tap do |words|
      return if words.length < 3
      db.store("global:start", words.first, :dup)
      db.store("global:end", words.last, :dup)
    end.each_cons(3) do |before, current, after|
      current.downcase!
      db.store("before:#{current}", before, :dup)
      db.store("after:#{current}", after, :dup)
    end
  end
end

#sentence(seed = random_word) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/brane.rb', line 28

def sentence(seed = random_word)
  sentence = [seed]
  
  while !starter?(sentence.first)
    if (words = db.values("before:#{sentence.first.downcase}")) && !words.empty?
      sentence.unshift(least_common(words))
    else
      break
    end
  end
  
  while !terminator?(sentence.last)
    if (words = db.values("after:#{sentence.last.downcase}")) && !words.empty?
      sentence.push(least_common(words))
    else
      break
    end
  end
  
  sentence.join(" ")
end

#sizeObject



50
51
52
# File 'lib/brane.rb', line 50

def size
  db.keys(prefix: "after:").size
end

#sleepObject



54
55
56
57
# File 'lib/brane.rb', line 54

def sleep
  db.flush
  db.close
end