“The Tie Between Ruby and Rust.”
Rutie — /ro͞oˈˌtī/rOOˈˌtɪ/rüˈˌtaɪ/
Integrate Ruby with your Rust application. Or integrate Rust with your Ruby application. This project allows you to do either with relative ease.
You are highly encouraged to read the source code for this project. Every method that has been
mapped from Ruby for public use in src/class/* is very well documented with example code.
This is the best way to take off running with Rutie. There are also integration examples in the
examples directory which are based off of this README.
This project is a continuation of:
methods! macro doesn't workFirst add the dependency to your Cargo.toml file.
[dependencies]
rutie = { version = "0.8", features = ["link-ruby"] }Then in your Rust program add VM::init() to the beginning of its code execution path
and begin to use Rutie.
use rutie::{Object, RString, VM};
fn try_it(s: &str) -> String {
let a = RString::new_utf8(s);
// The `send` method returns an AnyObject type.
let b = unsafe { a.send("reverse", &[]) };
// We must try to convert the AnyObject
// type back to our usable type.
match b.try_convert_to::() {
Ok(ruby_string) => ruby_string.to_string(),
Err(_) => "Fail!".to_string(),
}
}
#[test]
fn it_works() {
// Rust projects must start the Ruby VM
VM::init();
assert_eq!("selppa", try_it("apples"));
}
fn main() {}Running cargo test should have this test pass.
You can start a Ruby project with bundle gem rutie_ruby_example and then once
you change into that directory run cargo init --lib. Remove the TODOs from the gemspec
file. Add Rutie to the Cargo.toml file and define the lib type.
[dependencies]
rutie = { version = "xxx" }
[lib]
name = "rutie_ruby_example"
crate-type = ["cdylib"]Then edit your src/lib.rs file for your Rutie code.
use rutie::{class, methods, Class, Object, RString, VM};
class!(RutieExample);
methods!(
RutieExample,
_rtself,
fn pub_reverse(input: RString) -> RString {
let ruby_string = input.map_err(VM::raise_ex).unwrap();
RString::new_utf8(&ruby_string.to_string().chars().rev().collect::())
}
);
#[allow(non_snake_case)]
#[no_mangle]
pub extern "C" fn Init_rutie_ruby_example() {
Class::new("RutieExample", None).define(|klass| {
klass.def_self("reverse", pub_reverse);
});
}And that's it for the Rust side. When using the methods! macro or extern functions
make sure the method name won't clash with any others. This is why this example is prefixed with pub_.
Now you just need to load the library in Ruby. Add the rutie gem to your gemspec or Gemfile.
# gemspec
spec.add_dependency 'rutie', '~> 0.0.4'
# Gemfile
gem 'rutie', '~> 0.0.4'And then load the library in your main project file lib/rutie_ruby_example.rb.
require_relative "rutie_ruby_example/version"
require "rutie"
module RutieRubyExample
Rutie.new(:rutie_ruby_example).init "Init_rutie_ruby_example", __dir__
endThat's all you need to load your Ruby things from Rust. Now to write the test in
test/rutie_ruby_example_test.rb:
…If the class does not yet exist in Ruby you'll need to account for creating it before generating a new instance of it. This object is now compatible to be returned into Ruby directly from Rust/Rutie. Note that this definition is merely a Rust compatible representation of the Ruby object and doesn't define any Ruby methods which can be used from Ruby.
A preferred way to integrate a dynamic amount of parameters has not yet been implemented in Rutie, but you can still manage to get it done in the following way.
…This style of code is meant to be used outside of the methods! macro for now.
You may place this method on a class or module as you normally would from a methods! macro definition.
use rutie::{Class, Object, VM};
class!(Example);
// Code from above
fn main() {
VM::init();
Class::new("Example", None).define(|klass| {
klass.def("example_method", example_method);
});
}The Rutie project has in its plans to remove the need for anyone to write unsafe code for
variadic support and will likely be updating the methods! macro to support this natively.
For using Rutie versions less than 0.1 the change is simple. Replace all occurrences
of the string ruru with rutie in your program. And if you would like to use
ruby-sys code from Rutie rather than requiring ruby-sys you can change all existing
references to ruby_sys to rutie::rubysys.
You will have additional considerations to change like Error being removed. For that; change instances of type ruru::result::Error to rutie::AnyException.
Migrated parse_arguments from VM to util.
Internal changes util from binding and rubysys have been replaced to reduce confusion and reduce duplication.
crate::util::parse_arguments has been marked as unsafe, this is considered a breaking change in Rust.
I'm writing this section to bring to light that, as of this writing, the safety that Rust likes to guarantee for its crates and the Rutie crate aren't currently aligned. The typical Rust safety for libraries wrapping C code is to have one unsafe crate with a -sys extension in its name and then a crate that wraps that to make it safe.
Rutie is an official fork of the project Ruru and because of this a great deal of the decisions in design for the project remain unchanged. Rutie also brought in the ruby-sys crate and treats it as an internal private API/module; and yet shares it openly for other developers to have full control to design their own API on top of it.
One of the glaring things that Rutie has that goes against the Rust Philosophy on Safety is that any of the methods that call Ruby code, can potentially raise an exception, and don't return the type Option will panic when an exception is raised from Ruby… which kills the application process running. The way to avoid panics is simple: either guarantee the Ruby code you're running will never raise an exception, or Handling exceptions raised from Ruby in Rust code with "protect" methods that return the type Option. Anyone can implement this safety by reading and understanding how the protect methods are written in this library and working with them.
The important thing to consider as to “why doesn't every method guarantee the safety as Rust would prescribe to?” is that exception handling in Ruby is not a zero cost abstraction. So there is a cost in performance when you need to implement it. One can easily argue that the guarantee of safety is far more important than leaving the risk in the hands of inexperienced developers. But one could also argue that it is better to leave the choice of performance cost, and the fact that exception capturing is occasionally unnecessary, up to the developer. Seeing how the legacy of design decisions is largely inherited this project leans towards the latter argument where the choice of being absolutely safe everywhere vs some extra speed in performance is up to the developer.
I'm not opposed to this project being 100% safe, but that will be a major change and a totally different API with many decisions that need to come into play. Also since this project doesn't strictly adhere to Rust safety principles, as a crate library would be expected to be, this project will not reach the stable 1.0 release as the idea of stability and safety are hand in hand.
I do like safety guarantees and as much as possible new features and language APIs will be built toward this. You can see what the design of a safe API would look like by examining the Enumerator features that have been implemented in this way (largely wrapping method names with calls to protect_send).
Sometimes the Ruby binary built isn't the best for the system. Be sure to compile Ruby
for that system if this is the issue. With RVM do rvm reinstall --disable-binary with
your choice of Ruby version.
This is an indication that you haven't started a Ruby VM in Rust yet with VM::init();. Do this once
before using Ruby code from Rust.
This happens when the Rutie build is trying to link with libruby,
but it's not found on your library search path. Either add it to
LD_LIBRARY_PATH/DYLD_LIBRARY_PATH if you're building a standalone
program that calls VM::init(), or if you're building a library to
load into a running Ruby VM then you can disable linking by either
setting the environment variable NO_LINK_RUTIE, or enabling the
cargo feature no-link for Rutie in your Cargo.toml like this:
[dependencies]
rutie = {version="xxx", features=["no-link"]}methods! macro doesn't workThe way the macro is designed doesn't use the same parameter signatures you've provided
No open issues yet, or sync has not completed.