SEARCH
0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Prev | Current Page 189 | Next

Ola Bini

"Practical JRuby on Rails Web 2.0 Projects: Bringing Ruby on Rails to Java"

getGlobalVariables().set("$label",
JavaEmbedUtils.javaToRuby(runtime, 27));
runtime.evalScriptlet("puts 13 + $label");
}
}
At the moment, you need just two classes. First, the Ruby class is the central runtime.
The JavaEmbedUtils class provides some utilities that can be useful for working with Ruby
code.
So, what??™s happening here? Well, you define a new Java class and its main method. The
easiest way to get hold of a Ruby runtime is to call the getDefaultInstance method. It almost
always gives you what you want, if you don??™t want to redirect the engine??™s input and output,
or something fancy like that. That runtime is something you??™ll have to use extensively when
interacting with Ruby code.
The next line gets the GlobalVariables object, and sets the label global. The javaToRuby
method on JavaEmbedUtils is handy, because it??™s often a nasty procedure to convert a Java
object or primitive into its Ruby counterpart.
After you??™ve set the global, you call the method evalScriptlet. This is one of about a
dozen ways you can evaluate Ruby code with a runtime. Other versions include preparsing
the code and sending the parsed abstract syntax tree (AST) to the evaluator. There are other
possibilities, too.
To compile and run this code, place it in a file called c6/JRubyRuntime.java and execute
these commands:
javac -cp $JRUBY_HOME/lib/jruby.jar c6/JRubyRuntime.java
java -cp $JRUBY_HOME/lib/jruby.jar:. c6.JRubyRuntime
If you??™re lucky, you??™ll see the result of adding 13 to 27.


Pages:
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201