Sha256: 7b336c46d3c39a517b53c8f953906d33c257cb113251c498d82fa8d7a6c0720c

Contents?: true

Size: 1.98 KB

Versions: 3

Compression:

Stored size: 1.98 KB

Contents

# This file should only be required as needed. This file relies on v8,
# therubyracer. As this is not an essential feature of opal, this file
# will be loaded as needed, and when it is, an error is just thrown if
# the required gems are not installed.
begin
  require 'v8'
rescue LoadError => e
  abort "therubyracer is required for running javascript. Install it with `gem install therubyracer`"
end

require 'opal/context/loader'
require 'opal/context/console'
require 'opal/context/file_system'

module Opal
  class Context < V8::Context

    def initialize(opts = {})
      super opts
      setup_context
    end

    # Setup the context. This basically loads opal.js into our context, and
    # replace the loader etc with our custom loader for a Ruby environment. The
    # default "browser" loader cannot access files from disk.
    def setup_context
      self['console'] = Console.new
      load opal_js_path

      opal = self['opal']
      opal['loader'] = Loader.new opal, self
      # opal['fs'] = FileSystem.new opal, self

      eval "opal.require('core');", "(opal)"
    end

    # Returns the path to our main opal.js file. This makes it easier as
    # we will likely require this file more than once (once per context).
    def opal_js_path
      File.expand_path File.join(File.dirname(__FILE__), '..', '..', 'lib', 'opal.js')
    end

    # Start normal js repl
    def start_repl
      require 'readline'

      loop do
        line = Readline.readline '>> ', true
        puts "=> #{eval_ruby line, '(opal)'}"
      end
    end

    def eval_ruby(content, line = "")
      begin
        code = Opal::RubyParser.new(content).parse!.generate_top
        code = "var VM = opal.vm, self = VM.top, __FILE__ = '(opal)';" + code
        # puts code
        self['$opal_irb_result'] = eval code, line
        # self['$code'].to_s + "ww"
        eval "$opal_irb_result.$m.inspect($opal_irb_result);"
      rescue => e
        puts e
        puts("\t" + e.backtrace.join("\n\t"))
      end
    end
  end

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
opal-0.3.2 lib/opal/context.rb
opal-0.3.1 lib/opal/context.rb
opal-0.3.0 lib/opal/context.rb