Class: Opal::REPL

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

Constant Summary collapse

HISTORY_PATH =
File.expand_path('~/.opal-repl-history')

Instance Method Summary collapse

Constructor Details

#initializeREPL

Returns a new instance of REPL.


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

def initialize
  begin
    require 'mini_racer'
  rescue LoadError
    abort 'opal-repl depends on mini_racer gem, which is not currently installed'
  end

  begin
    require 'readline'
  rescue LoadError
    abort 'opal-repl depends on readline, which is not currently available'
  end

  MiniRacer::Platform.set_flags! :harmony

  @history = File.exist?(HISTORY_PATH)
end

Instance Method Details

#load_file(filename) ⇒ Object


37
38
39
40
# File 'opal/lib/opal/repl.rb', line 37

def load_file(filename)
  raise "file does not exist: #{filename}" unless File.exist? filename
  eval_ruby File.read(filename)
end

#load_opalObject


47
48
49
50
51
52
53
# File 'opal/lib/opal/repl.rb', line 47

def load_opal
  v8.attach('console.log', method(:puts).to_proc)
  v8.attach('console.warn', method(:warn).to_proc)
  v8.attach('crypto.randomBytes', method(:random_bytes).to_proc)
  v8.eval Opal::Builder.new.build('opal').to_s
  v8.attach('Opal.exit', method(:exit).to_proc)
end

#random_bytes(bytes) ⇒ Object

A polyfill so that SecureRandom works in repl correctly.


43
44
45
# File 'opal/lib/opal/repl.rb', line 43

def random_bytes(bytes)
  ::SecureRandom.bytes(bytes).split('').map(&:ord)
end

#run(filename = nil) ⇒ Object


28
29
30
31
32
33
34
35
# File 'opal/lib/opal/repl.rb', line 28

def run(filename = nil)
  load_opal
  load_file(filename) if filename
  load_history
  run_input_loop
ensure
  dump_history
end

#run_input_loopObject


60
61
62
63
64
65
66
67
68
69
70
# File 'opal/lib/opal/repl.rb', line 60

def run_input_loop
  # on SIGINT lets just return from the loop..
  previous_trap = trap('SIGINT') { return }

  while (line = readline)
    run_line(line)
  end

ensure
  trap('SIGINT', previous_trap || 'DEFAULT')
end

#run_line(line) ⇒ Object


55
56
57
58
# File 'opal/lib/opal/repl.rb', line 55

def run_line(line)
  result = eval_ruby(line)
  puts "=> #{result}"
end