Module: Opal::IRB

Defined in:
opal/opal/corelib/irb.rb

Defined Under Namespace

Classes: Silencer

Constant Summary collapse

LINEBREAKS =
[
  'unexpected token $end',
  'unterminated string meets end of file'
].freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Attribute Details

#outputObject

Returns the value of attribute output.



40
41
42
# File 'opal/opal/corelib/irb.rb', line 40

def output
  @output
end

Class Method Details

.browser?Boolean

Returns:



78
79
80
# File 'opal/opal/corelib/irb.rb', line 78

def self.browser?
  `typeof(document) !== 'undefined' && typeof(prompt) !== 'undefined'`
end

.ensure_loaded(library) ⇒ Object



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
# File 'opal/opal/corelib/irb.rb', line 8

def self.ensure_loaded(library)
  return if `Opal.loaded_features`.include? library

  version = if RUBY_ENGINE_VERSION.include? 'dev'
              'master'
            else
              RUBY_ENGINE_VERSION
            end

  url = "https://cdn.opalrb.com/opal/#{version}/#{library}.js"

  %x{
    var libcode;

    if (typeof XMLHttpRequest !== 'undefined') { // Browser
      var r = new XMLHttpRequest();
      r.open("GET", url, false);
      r.send('');
      libcode = r.responseText;
    }
    else {
      #{::Kernel.raise "You need to provision #{library} yourself in this environment"}
    }

    (new Function('Opal', libcode))(Opal);

    Opal.require(library);
  }

  ::Kernel.raise "Could not load #{library} for some reason" unless `Opal.loaded_features`.include? library
end

.prepare_console(&block) ⇒ Object



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
68
69
70
71
72
73
74
75
76
# File 'opal/opal/corelib/irb.rb', line 42

def self.prepare_console(&block)
  self.output = ''

  original = {
    $stdout => ->(i) { $stdout = i },
    $stderr => ->(i) { $stderr = i },
  }

  # Prepare a better prompt experience for a browser
  if browser?
    original.each do |pipe, pipe_setter|
      new_pipe = pipe.dup
      new_pipe.write_proc = proc do |str|
        self.output += str
        self.output = output.split("\n").last(30).join("\n")
        self.output += "\n" if str.end_with? "\n"

        pipe.write_proc.call(str)
      end
      new_pipe.tty = false
      pipe_setter.call(new_pipe)
    end

    original_read_proc = $stdin.read_proc
    $stdin.read_proc = `function(s) { var p = prompt(#{output}); if (p !== null) return p + "\n"; return nil; }`
  end

  yield
ensure
  original.each do |pipe, pipe_setter|
    pipe_setter.call(pipe)
  end
  $stdin.read_proc = original_read_proc
  self.output = ''
end