Sha256: 3e3be3beaf5be5e52fecd0a37bf1bb7f076bbd4d23c15ccde73d2eb121feb711

Contents?: true

Size: 1.99 KB

Versions: 7

Compression:

Stored size: 1.99 KB

Contents

#!/usr/bin/env ruby

require 'opal'

module Opal
  class V8Context
    def initialize
      @builder = Opal::Builder.new
      @history_path = File.expand_path('~/.opal-repl-history')
      @history = File.exist?(@history_path)
    end

    def run(filename = nil)
      return if @v8

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

      @v8 = MiniRacer::Context.new
      @v8.eval Opal::Builder.new.build('opal').to_s

      if filename
        if File.exist? filename
          eval_ruby File.read(filename)
        else
          fail "file does not exist: #{filename}"
        end
      end

      run_repl
    end

    def log(*str)
      puts(*str)
    end

    def run_repl
      require 'readline'
      load_history

      loop do
        # on SIGINT lets just return from the loop..
        trap('SIGINT') { finish; return }
        line = Readline.readline '>> ', true

        # if we type exit, then we need to close down context
        if line == 'exit' or line.nil?
          break
        end

        puts "=> #{eval_ruby line}"
      end

      finish
    end

    def eval_ruby(str)
      code = Opal::Builder.new.build_str(str, '(irb)', :irb => true, :const_missing => true)
      code.processed[0...-1].each { |c| @v8.eval(c.to_s) }
      @v8.eval "var $_result = #{code.processed.last.to_s} ($_result == null ? 'nil' : $_result.$inspect());"
    rescue Exception => e
      puts "#{e.message}\n\t#{e.backtrace.join("\n\t")}"
    end

    def load_history
      return unless @history
      File.read(@history_path).lines.each { |line| Readline::HISTORY.push line.strip }
    end

    def dump_history
      return unless @history
      length = (Readline::HISTORY.size > 1000) ? 1000 : Readline::HISTORY.size
      File.write(@history_path, Readline::HISTORY.to_a[-length..-1].join("\n"))
    end

    def finish
      dump_history
      @v8 = nil
    end
  end
end

Opal::V8Context.new.run ARGV.first

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
opal-1.0.5 exe/opal-repl
opal-1.0.4 exe/opal-repl
opal-1.0.3 exe/opal-repl
opal-1.0.2 exe/opal-repl
opal-1.0.1 exe/opal-repl
opal-1.0.0 exe/opal-repl
opal-1.0.0.beta1 exe/opal-repl