Skip to content

Commit a15ed49

Browse files
committedDec 7, 2014
Add RUBY_ENGINE handling to compiler directives
1 parent e3e5c62 commit a15ed49

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
 

‎docs/CompilerDirectives.md

+45
Original file line numberDiff line numberDiff line change
@@ -78,3 +78,48 @@ files to be required and generated in the output. The obvious example of
7878
this is requiring javascript source files. Javascript sources are
7979
treated as first class citizens in Opal. The Opal gem also supports
8080
compiling `.erb` files using the same process.
81+
82+
## Opal Specific Code Compilation
83+
84+
A special case `if` and `unless` statements can hide or show blocks of
85+
code from the Opal compiler. These check against `RUBY_ENGINE` or
86+
`RUBY_PLATFORM`. As these are valid ruby statements against constants
87+
that exist in all ruby runtimes, they will not affect any running code:
88+
89+
if RUBY_ENGINE == 'opal'
90+
# this code compiles
91+
else
92+
# this code never compiles
93+
end
94+
95+
Unless statements are also supported:
96+
97+
unless RUBY_ENGINE == 'opal'
98+
# this code will not run
99+
end
100+
101+
Also `!=` statements work:
102+
103+
if RUBY_ENGINE != 'opal'
104+
puts "do not run this code"
105+
end
106+
107+
These blocks of code dont run at all at runtime, but they also never
108+
compile so will never be in the output javascript code. This is
109+
particularly useful for using code in both mri and Opal.
110+
111+
Some uses are:
112+
113+
* Avoid `require` statements being picked up by Opal compile time
114+
require handling.
115+
116+
* To stop certain requires taking place for opal (and vice-versa for
117+
shared libraries).
118+
119+
* To wrap x-strings which might break in compiled javascript output.
120+
121+
* To simply avoid compiling large blocks of code that are not needed
122+
in the javascript/opal version of an app.
123+
124+
In all these examples `RUBY_PLATFORM` can be used instead of
125+
`RUBY_ENGINE`.

0 commit comments

Comments
 (0)
Please sign in to comment.