Skip to content

Instantly share code, notes, and snippets.

@TJC
Created June 20, 2019 04:43
Show Gist options
  • Save TJC/377f51e519e8a93c9dbb49b5d75a7a0f to your computer and use it in GitHub Desktop.
Save TJC/377f51e519e8a93c9dbb49b5d75a7a0f to your computer and use it in GitHub Desktop.
Run a Ruby function from Scala and get the result.
#!ruby
def entrypoint(arg)
"I received #{arg}"
end
libraryDependencies ++= Seq(
"org.jruby" % "jruby" % "9.2.7.0",
)
import org.jruby.embed.ScriptingContainer
object RubyRunner {
def rubyScript = io.Source.fromFile("demo.rb").mkString
def main(args: Array[String]): Unit = {
val result = runScript(rubyScript, "hello world")
println(s"Ruby returned: $result")
}
// this runs a Ruby script, calling into a method called "entrypoint" with one argument.
def runScript(script: String, args: String): String = {
// Boot up a scripting container:
val container = new ScriptingContainer()
// Load the script from file into Ruby interpreter:
container.runScriptlet(script)
// Call a method in Ruby with an argument, and expect a string reply:
// receiver is Ruby class; null = top-level self
container.callMethod[String](null, "entrypoint", args, classOf[String])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment