Class: Runner::MonkeyRun

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(monkey_service, runtime) ⇒ MonkeyRun

Returns a new instance of MonkeyRun.



18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/tasks/engine.rb', line 18

def initialize(monkey_service, runtime)
  @monkey_words = {}
  @monkey_service = monkey_service
  @runtime = runtime.to_i

  @monkey_service.add_observer self

  @thread = Thread.new do
    go
    sleep @runtime
  end
end

Instance Attribute Details

#monkey_serviceObject (readonly)

Returns the value of attribute monkey_service.



16
17
18
# File 'lib/tasks/engine.rb', line 16

def monkey_service
  @monkey_service
end

#monkey_wordsObject (readonly)

Returns the value of attribute monkey_words.



16
17
18
# File 'lib/tasks/engine.rb', line 16

def monkey_words
  @monkey_words
end

#runtimeObject (readonly)

Returns the value of attribute runtime.



16
17
18
# File 'lib/tasks/engine.rb', line 16

def runtime
  @runtime
end

#threadObject (readonly)

Returns the value of attribute thread.



16
17
18
# File 'lib/tasks/engine.rb', line 16

def thread
  @thread
end

Instance Method Details

#goObject



31
32
33
34
35
36
# File 'lib/tasks/engine.rb', line 31

def go
  @monkey_service.add(MonkeyFactory.create(:groucho))
  @monkey_service.add(MonkeyFactory.create(:harpo))
  @monkey_service.add(MonkeyFactory.create(:chico))
  @monkey_service.add(MonkeyFactory.create(:zeppo))
end

#update(_time, action, param) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/tasks/engine.rb', line 38

def update(_time, action, param)
  return unless param.is_a?(Hash) && param.key?(:action)

  if param[:action].is_a?(MonkeyActionType) && action == :action_completed
    monkey = param[:action].monkey.monkey_symbol.to_s
    is_word = param[:action].keyboard_input.is_word
    word = param[:action].keyboard_input.input_to_s

    message = "Monkey: [#{monkey.capitalize}] | Is Word: [#{is_word}] | Value: [#{word.capitalize}]"
    if is_word
      @monkey_words[monkey] = {} unless @monkey_words[monkey]
      @monkey_words[monkey][word] = 0 unless @monkey_words.dig(monkey, word)
      times = @monkey_words[monkey][word] += 1
      puts "#{message} | Times: #{times} so far!".colorize(color: :green, mode: :bold)
      return
    end

    puts message
  end
rescue StandardError => e
  puts "StandardError: #{e}"
end