1

I'm building an application that will be hosted both as a stand-alone app as well as running within the web browser. This means that certain classes should be implemented differently (but used in the same way). Example:

If OPAL_RB
  require 'javascript_aware_lib'
else
  require 'native_lib'
end

The problem with this is, Ruby will evaluate this at run-time, but Opal will evaluate it at compile time. If this was not so, I could simply use a rescue clause:

begin   
  RUBY_ENGINE_VERSION
  #opal requires goes here
rescue
  # MRI Ruby requires goes here 
end

So, to put things simply: Is there any kind of directive or work-around to keep Opal from evaluating a block of code? Thanks.

mikabytes
  • 1,818
  • 2
  • 18
  • 30

2 Answers2

1

Use unless RUBY_ENGINE == 'opal', which is actually skipped at compilation time. This makes it effective to skip also unsupported syntax. if, else and RUBY_PLATFORM are also supported.

Example:

if RUBY_ENGINE == 'opal'
  require 'javascript_aware_lib'
else
  require 'native_lib'
end

Some relevant code (for the curious)

Compiler handling the AST: https://github.com/opal/opal/blob/ef570e3ddde9bddc48cc0f94c00e80576140850f/lib/opal/nodes/if.rb#L10-L15

Changelog: https://github.com/opal/opal/blob/8a023f057799fd68fecb3371b52950c7392d469c/CHANGELOG.md#060-2014-03-05

Specs: https://github.com/opal/opal/blob/0aef3c6c7a5db8ff86c8f786a5ea6885ea2b12dc/spec/cli/compiler_spec.rb#L86-L121

Elia Schito
  • 989
  • 7
  • 18
0

I just found this code

if defined?(Opal) && defined?(File)  
  Opal.append_path File.expand_path('.', File.dirname(__FILE__))
end

in this interesting blogpost on writing cross ruby gems for MRI, opalrb and RubyMotion. Might be interesting for you as well. It uses the presence of the Opal class to determine the ruby interpreter.

Patru
  • 4,481
  • 2
  • 32
  • 42
  • The post is good but the code is quite weak, I already wrote to the author to fix it by relying on `RUBY_ENGINE` instead. – Elia Schito Aug 08 '14 at 13:36