Have you ever considered rewriting some parts of your ~~slow~~ Ruby application?
Just replace your Ruby application with Rust, method by method, class by class. It does not require you to change the interface of your classes or to change any other Ruby code.
As simple as Ruby, as efficient as Rust.
String#blank?
methodThe fast String#blank?
implementation by Yehuda Katz
```rust,no_run
extern crate ruru;
use ruru::{Boolean, Class, Object, RString};
methods!( RString, itself,
fn stringisblank() -> Boolean { Boolean::new(itself.tostring().chars().all(|c| c.iswhitespace())) } );
pub extern fn initializestring() { Class::fromexisting("String").define(|itself| { itself.def("blank?", stringisblank); }); } ```
Since 0.8.0 safe conversions are available for built-in Ruby types and for custom types.
Let's imagine that we are writing an HTTP server. It should handle requests which are passed from Ruby side.
Any object which responds to #body
method is considered as a valid request.
```rust,no_run
extern crate ruru;
use std::error::Error; use ruru::{Class, Object, RString, VerifiedObject, VM};
class!(Request);
impl VerifiedObject for Request {
fn iscorrecttype
fn error_message() -> &'static str {
"Not a valid request"
}
}
class!(Server);
methods!( Server, itself,
fn process_request(request: Request) -> RString {
let body = request
.and_then(|request| request.send("body", vec![]).try_convert_to::<RString>())
.map(|body| body.to_string());
// Either request does not respond to `body` or `body` is not a String
if let Err(ref error) = body {
VM::raise(error.to_exception(), error.description());
}
let formatted_body = format!("[BODY] {}", body.unwrap());
RString::new(&formatted_body)
}
);
pub extern fn initializeserver() { Class::new("Server", None).define(|itself| { itself.def("processrequest", process_request); }); } ```
Wrap Server
s to RubyServer
objects
```rust,no_run
use ruru::{AnyObject, Class, Fixnum, Object, RString, VM};
// The structure which we want to wrap pub struct Server { host: String, port: u16, }
impl Server { fn new(host: String, port: u16) -> Self { Server { host: host, port: port, } }
fn host(&self) -> &str {
&self.host
}
fn port(&self) -> u16 {
self.port
}
}
wrappablestruct!(Server, ServerWrapper, SERVERWRAPPER);
class!(RubyServer);
methods!( RubyServer, itself,
fn ruby_server_new(host: RString, port: Fixnum) -> AnyObject {
let server = Server::new(host.unwrap().to_string(),
port.unwrap().to_i64() as u16);
Class::from_existing("RubyServer").wrap_data(server, &*SERVER_WRAPPER)
}
fn ruby_server_host() -> RString {
let host = itself.get_data(&*SERVER_WRAPPER).host();
RString::new(host)
}
fn ruby_server_port() -> Fixnum {
let port = itself.get_data(&*SERVER_WRAPPER).port();
Fixnum::new(port as i64)
}
);
fn main() { let dataclass = Class::fromexisting("Data");
Class::new("RubyServer", Some(&data_class)).define(|itself| {
itself.def_self("new", ruby_server_new);
itself.def("host", ruby_server_host);
itself.def("port", ruby_server_port);
});
} ```
Ruru provides a way to enable true parallelism for Ruby threads by releasing GVL (GIL).
It means that a thread with released GVL runs in parallel with other threads without being interrupted by GVL.
Current example demonstrates a "heavy" computation (2 * 2
for simplicity) run in parallel.
```rust,no_run
use ruru::{Class, Fixnum, Object, VM};
class!(Calculator);
methods!( Calculator, itself,
fn heavy_computation() -> Fixnum {
let computation = || { 2 * 2 };
let unblocking_function = || {};
// release GVL for current thread until `computation` is completed
let result = VM::thread_call_without_gvl(
computation,
Some(unblocking_function)
);
Fixnum::new(result)
}
);
fn main() { Class::new("Calculator", None).define(|itself| { itself.def("heavycomputation", heavycomputation); }); } ```
Let's say you have a Calculator
class.
```ruby class Calculator def pow3(number) (1..number).eachwith_object({}) do |index, hash| hash[index] = index ** 3 end end end
Calculator.new.pow_3(5) #=> { 1 => 1, 2 => 8, 3 => 27, 4 => 64, 5 => 125 } ```
You have found that it's very slow to call pow_3
for big numbers and decided to replace the whole class
with Rust.
```rust,no_run
extern crate ruru;
use std::error::Error; use ruru::{Class, Fixnum, Hash, Object, VM};
class!(Calculator);
methods!( Calculator, itself,
fn pow_3(number: Fixnum) -> Hash {
let mut result = Hash::new();
// Raise an exception if `number` is not a Fixnum
if let Err(ref error) = number {
VM::raise(error.to_exception(), error.description());
}
for i in 1..number.unwrap().to_i64() + 1 {
result.store(Fixnum::new(i), Fixnum::new(i.pow(3)));
}
result
}
);
pub extern fn initializecalculator() { Class::new("Calculator", None).define(|itself| { itself.def("pow3", pow_3); }); } ```
Ruby:
```ruby
Calculator.new.pow_3(5) #=> { 1 => 1, 2 => 8, 3 => 27, 4 => 64, 5 => 125 } ```
Nothing has changed in the API of class, thus there is no need to change any code elsewhere in the app.
If the Calculator
class from the example above has more Ruby methods, but we want to
replace only pow_3
, use Class::from_existing()
rust,ignore
Class::from_existing("Calculator").define(|itself| {
itself.def("pow_3", pow_3);
});
```rust,norun Class::new("Hello", None).define(|itself| { itself.constset("GREETING", &RString::new("Hello, World!").freeze());
itself.attr_reader("reader");
itself.def_self("greeting", greeting);
itself.def("many_greetings", many_greetings);
itself.define_nested_class("Nested", None).define(|itself| {
itself.def_self("nested_greeting", nested_greeting);
});
}); ```
Which corresponds to the following Ruby code:
```ruby class Hello GREETING = "Hello, World".freeze
attr_reader :reader
def self.greeting # ... end
def many_greetings # ... end
class Nested def self.nested_greeting # ... end end end ```
See documentation for Class
and Object
for more information.
Getting an account balance of some User
whose name is John and who is 18 or 19 years old.
```ruby default_balance = 0
accountbalance = User .findby(age: [18, 19], name: 'John') .account_balance
accountbalance = defaultbalance unless accountbalance.isa?(Fixnum) ```
```rust,no_run
extern crate ruru;
use ruru::{Array, Class, Fixnum, Hash, Object, RString, Symbol};
fn main() { let default_balance = 0; let mut conditions = Hash::new();
conditions.store(
Symbol::new("age"),
Array::new().push(Fixnum::new(18)).push(Fixnum::new(19))
);
conditions.store(
Symbol::new("name"),
RString::new("John")
);
// Fetch user and his balance
// and set it to 0 if balance is not a Fixnum (for example `nil`)
let account_balance =
Class::from_existing("User")
.send("find_by", vec![conditions.to_any_object()])
.send("account_balance", vec![])
.try_convert_to::<Fixnum>()
.map(|balance| balance.to_i64())
.unwrap_or(default_balance);
} ```
Check out Documentation for many more examples!
No support of native Ruby types;
No way to create a standalone application to run the Ruby VM separately;
No way to call your Ruby code from Rust;
Warning! The crate is a WIP.
It is recommended to use Thermite gem, a Rake-based helper for building and distributing Rust-based Ruby extensions.
To be able to use Ruru, make sure that your Ruby version is 2.3.0 or higher.
Your local MRI copy has to be built with the --enable-shared
option. For
example, using rbenv:
bash
CONFIGURE_OPTS=--enable-shared rbenv install 2.3.0
Add Ruru to Cargo.toml
toml
[dependencies]
ruru = "0.9.0"
Compile your library as a dylib
toml
[lib]
crate-type = ["dylib"]
Create a function which will initialize the extension
```rust,ignore
pub extern fn initializemyapp() { Class::new("SomeClass");
// ... etc } ```
Build extension
bash
$ cargo build --release
or using Thermite
bash
$ rake thermite:build
On the ruby side, open the compiled dylib
and call the function to initialize extension
```ruby require 'fiddle'
library = Fiddle::dlopen('pathtodylib/libmy_library.dylib')
Fiddle::Function.new(library['initializemyapp'], [], Fiddle::TYPE_VOIDP).call ```
Ruru is ready :heart:
If you have any questions, join Ruru on Gitter
MIT License
Copyright (c) 2015-2016 Dmitry Gritsay
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Icon is designed by Github.