mrusty::mruby_class! [] [src]

macro_rules! mruby_class {
    ( $mruby:expr, $mrname:expr ) => { ... };
    ( $mruby:expr, $mrname:expr, { $( $rest:tt )* } ) => { ... };
}

A macro that comes in handy when defining a pure mruby Class. It lets you define and control pure mruby types and returns the newly defined Class, unlike mrusty_class! which also handles Rust types.

The macro takes an mruby MrubyType, an mruby Class name, and a block as arguments. Inside of the block you can define mruby methods with the def! and def_self! helpers which are not visible outside of this macro.

def! and def_self! are analogous to mrfn! which has more usage examples.

Examples

Use def! to define mruby instance methods.

Note: mruby argument is optional.

use mrusty::{Mruby, MrubyImpl};

let mruby = Mruby::new();

mruby_class!(mruby, "Container", {
    def!("initialize", |mruby, slf: Value, v: i32| {
        slf.set_var("value", mruby.fixnum(v));

        slf
    });

    def!("value", |mruby, slf: Value| {
        slf.get_var("value").unwrap()
    });
});

let result = mruby.run("Container.new(3).value").unwrap();

assert_eq!(result.to_i32().unwrap(), 3);


Use def_self! to define mruby class methods.

Note: mruby argument is optional.

use mrusty::{Mruby, MrubyImpl};

let mruby = Mruby::new();

mruby_class!(mruby, "Container", {
    def_self!("hi", |mruby, slf: Value| {
        mruby.string("hi")
    });
});

let result = mruby.run("Container.hi").unwrap();

assert_eq!(result.to_str().unwrap(), "hi");


mruby_class! also works on mruby primitive types.

use mrusty::{Mruby, MrubyImpl};

let mruby = Mruby::new();

mruby_class!(mruby, "Fixnum", {
    def!("digits", |mruby, slf: i32| {
        if slf == 0 {
            mruby.array(vec![mruby.fixnum(0)])
        } else {
            let mut number = slf;
            let mut digits = vec![];

            while number != 0 {
                digits.push(mruby.fixnum(number % 10));

                number /= 10;
            }

            mruby.array(digits)
        }
    });
});

let result = mruby.run("123.digits.inject(:+)").unwrap();

assert_eq!(result.to_i32().unwrap(), 6);