Macro magnus::function

source ·
macro_rules! function {
    ($name:expr, -2) => { ... };
    ($name:expr, -1) => { ... };
    ($name:expr, 0) => { ... };
    ($name:expr, 1) => { ... };
    ($name:expr, 2) => { ... };
    ($name:expr, 3) => { ... };
    ($name:expr, 4) => { ... };
    ($name:expr, 5) => { ... };
    ($name:expr, 6) => { ... };
    ($name:expr, 7) => { ... };
    ($name:expr, 8) => { ... };
    ($name:expr, 9) => { ... };
    ($name:expr, 10) => { ... };
    ($name:expr, 11) => { ... };
    ($name:expr, 12) => { ... };
    ($name:expr, 13) => { ... };
    ($name:expr, 14) => { ... };
    ($name:expr, 15) => { ... };
    ($name:expr, 16) => { ... };
    ($name:expr, $arity:expr) => { ... };
}
Expand description

Wrap a Rust function item with Ruby type conversion and error handling, ignoring Ruby’s self argument.

This macro wraps the given function and returns a function pointer implementing the Method trait, suitable for passing to functions that define Ruby methods such as define_method.

Ruby code implicitly always has a self parameter available. In the extention API this is passed explicitly. The wrapper this macro generates ignores that argument, and does not pass it to the wrapped function.

The values -2 and -1 for arity have special meaning. Both indicate functions with any number of arguments, with -2 the arguments are passed as a RArray, with -1 they are passed as a slice of Values. Arity of -1 can be used with scan_args and get_kwargs for more complex method signatures.

AritySignature
-2fn(arguments: RArray) -> Result<R, Error>
-1fn(arguments: &[Value]) -> Result<R, Error>
0fn()-> Result<R, Error>
1fn(arg1: T) -> Result<R, Error>
2fn(arg1: T, arg2: U) -> Result<R, Error>
16

Where T, U, and so on are any types that implement TryConvert, and R implements Into<Value>. It is also possible to return just R rather than a Result for functions that will never error, and omit the return value (i.e. return ()) for a function that returns nil to Ruby. See ReturnValue for more details on what can be returned.

See the method macro for cases where the self argument is required.

Examples

fn distance(a: (f64, f64), b: (f64, f64)) -> f64 {
    ((b.0 - a.0).powi(2) + (b.0 - a.0).powi(2)).sqrt()
}

#[magnus::init]
fn init() {
    magnus::define_global_function("distance", magnus::function!(distance, 2));
}