summaryrefslogtreecommitdiff
path: root/controllers/interfaces/repl.rb
blob: 7b53eb22a8cf5126e4f14e954ba3c8ad64998d37 (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# frozen_string_literal: true

require 'pry'
require 'rainbow'

require_relative '../../logic/helpers/hash'

module NanoBot
  module Controllers
    module Interfaces
      module REPL
        def self.start(cartridge, session)
          if Logic::Helpers::Hash.fetch(
            cartridge, %i[interfaces repl prefix]
          )
            session.print(Logic::Helpers::Hash.fetch(cartridge,
                                                     %i[interfaces repl prefix]))
          end

          session.boot(mode: 'repl')

          session.print(Logic::Helpers::Hash.fetch(cartridge, %i[interfaces repl postfix]) || "\n")

          session.flush

          prompt = build_prompt(cartridge[:interfaces][:repl][:prompt])

          Pry.config.prompt = Pry::Prompt.new(
            'REPL',
            'REPL Prompt',
            [proc { prompt }, proc { 'MISSING INPUT' }]
          )

          Pry.commands.block_command(/(.*)/, 'handler') do |line|
            if Logic::Helpers::Hash.fetch(
              cartridge, %i[interfaces repl prefix]
            )
              session.print(Logic::Helpers::Hash.fetch(
                              cartridge, %i[interfaces repl prefix]
                            ))
            end

            session.evaluate_and_print(line, mode: 'repl')
            session.print(Logic::Helpers::Hash.fetch(cartridge, %i[interfaces repl postfix]) || "\n")
            session.flush
          end

          Pry.start
        end

        def self.build_prompt(prompt)
          result = ''

          prompt.each do |partial|
            result += if partial[:color]
                        Rainbow(partial[:text]).send(partial[:color])
                      else
                        partial[:text]
                      end
          end

          result
        end
      end
    end
  end
end