Class: Keisan::Repl

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

Constant Summary collapse

COMMANDS =
%w(
  reset
  quit
  variables
  functions
  allow_recursive
).freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeRepl

Returns a new instance of Repl.



16
17
18
19
20
# File 'lib/keisan/repl.rb', line 16

def initialize
  @running = true
  initialize_completion_commands
  reset
end

Instance Attribute Details

#calculatorObject (readonly)

Returns the value of attribute calculator.



14
15
16
# File 'lib/keisan/repl.rb', line 14

def calculator
  @calculator
end

Instance Method Details

#get_commandObject



36
37
38
# File 'lib/keisan/repl.rb', line 36

def get_command
  Readline.readline("keisan> ", true)
end

#output_error(error) ⇒ Object



68
69
70
# File 'lib/keisan/repl.rb', line 68

def output_error(error)
  puts CodeRay.encode(error.class.to_s, :ruby, :terminal) + ": " + CodeRay.encode("\"#{error.message}\"", :ruby, :terminal)
end

#output_functionsObject



78
79
80
81
82
# File 'lib/keisan/repl.rb', line 78

def output_functions
  function_registry.locals.each do |name, function|
    puts CodeRay.encode("#{name}(#{function.arguments.join(', ')}) = #{function.expression.to_s}", :ruby, :terminal)
  end
end

#output_result(result) ⇒ Object



64
65
66
# File 'lib/keisan/repl.rb', line 64

def output_result(result)
  puts "=> " + CodeRay.encode(result.to_s, :ruby, :terminal)
end

#output_variablesObject



72
73
74
75
76
# File 'lib/keisan/repl.rb', line 72

def output_variables
  variable_registry.locals.each do |name, variable|
    puts CodeRay.encode("#{name} = #{variable.value}", :ruby, :terminal)
  end
end

#process_command(command) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/keisan/repl.rb', line 40

def process_command(command)
  command = command.strip
  return if command.empty?

  case command
  when /\Areset\z/i
    reset
  when /\Aquit\z/i
    @running = false
  when /\Avariables\z/i
    output_variables
  when /\Afunctions\z/i
    output_functions
  when /\Aallow_recursive\z/i
    calculator.allow_recursive!
  else
    begin
      output_result calculator.simplify(command)
    rescue StandardError => error
      output_error error
    end
  end
end

#resetObject



22
23
24
# File 'lib/keisan/repl.rb', line 22

def reset
  @calculator = Calculator.new
end

#startObject



26
27
28
29
30
31
32
33
34
# File 'lib/keisan/repl.rb', line 26

def start
  while @running
    command = get_command

    # ctrl-d should break out
    break if command.nil?
    process_command command
  end
end