Class: Hesabu::Solver

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

Instance Method Summary collapse

Constructor Details

#initializeSolver

Returns a new instance of Solver.



3
4
5
# File 'lib/hesabu/solver.rb', line 3

def initialize
  @equations = {}
end

Instance Method Details

#add(name, raw_expression) ⇒ Object



7
8
9
10
11
12
# File 'lib/hesabu/solver.rb', line 7

def add(name, raw_expression)
  if raw_expression.nil? || name.nil?
    raise Hesabu::ArgumentError, "name or expression can't be nil : '#{name}', '#{raw_expression}'"
  end
  @equations[name] = raw_expression.to_s
end

#handle_error(solution) ⇒ Object



30
31
32
33
34
35
36
37
# File 'lib/hesabu/solver.rb', line 30

def handle_error(solution)
  error = solution["errors"].first
  message = "In equation #{error['source']} " + error["message"] + " #{error['source']} := #{error['expression']}"

  err = Hesabu::Error.new(message)
  err.errors = solution["errors"]
  raise err
end

#log_everything(exit_status, result) ⇒ Object



39
40
41
42
43
44
45
# File 'lib/hesabu/solver.rb', line 39

def log_everything(exit_status, result)
  puts ["**************",
        "exit_status:#{exit_status}",
        @equations.to_json,
        "=> ",
        result].join("\n")
end

#solve!Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/hesabu/solver.rb', line 14

def solve!
  return {} if @equations.empty?
  result = nil
  IO.popen(HESABUCLI, mode = "r+") do |io|
    io.write Hesabu::MultiJSON.generate(@equations)
    io.close_write # let the process know you've given it all the data
    result = io.read
  end
  solution = Hesabu::MultiJSON.parse(result)
  exit_status = $CHILD_STATUS.exitstatus

  log_everything(exit_status, result) if ENV["HESABU_DEBUG"] || exit_status != 0
  handle_error(solution) if exit_status != 0
  solution
end