Wednesday, May 13, 2015

Ruby, Rust, and Rake: A Small Tale

So in getting Ruby to call Rust functions I came across a small headache when using Rake to compile my Rust and run my Ruby in one fell swoop.

I got my Rust file to compile correctly by making a system call like so:

    rake :run do
      `rustc func.rs --crate-type=dylib`
      load 'script.rb'
    end

But of course, being new to Rust, I invariably started causing the compiler to error out.  I wanted my Ruby script to run only if my Rust file compiled correctly, so I tried something like this:

    rake :run do
      code = `rustc func.rs --crate-type=dylib`
      load 'script.rb' if code
    end

But it didn't work!  Come to find out, the compilation was always storing the empty string "" into error.

The solution was to use system('command') instead of the backticks:

    rake :run do
      code = system('rustc func.rs --crate-type=dylib')
      load 'script.rb' if code
    end

And now it works perfectly!  Now to clean it up:

    rake :run do
      load 'script.rb' if system('rustc func.rs --crate-type=dylib')
    end

I hope that helps someone else running into this (tiny) headache.

Tl:dr: use Kernel.system to compile Rust from Rake if you want to conditionally run more code.

No comments:

Post a Comment