macro_rules! method {
($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.
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. As a result there is always an
extra self
argument before the arguments explitly passed in Ruby, and the
number of Rust argument will be one more than the Ruby arity.
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 Value
s.
Arity of -1
can be used with scan_args
and get_kwargs
for more complex method
signatures.
Arity | Signature |
---|---|
-2 | fn(rb_self: T, arguments: RArray) -> Result<R, Error> |
-1 | fn(rb_self: T, arguments: &[Value]) -> Result<R, Error> |
0 | fn(rb_self: T) -> Result<R, Error> |
1 | fn(rb_self: T, arg1: U) -> Result<R, Error> |
2 | fn(rb_self: T, arg1: U, arg2: V) -> Result<R, Error> |
… | … |
16 | … |
Where T
, U
, V
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 function
macro for cases where there is no
need to handle the self
argument.
Examples
use magnus::{define_class, method, prelude::*, Error};
fn rb_is_blank(rb_self: String) -> bool {
rb_self.contains(|c: char| !c.is_whitespace())
}
#[magnus::init]
fn init() -> Result<(), Error> {
let class = define_class("String", Default::default())?;
class.define_method("blank?", method!(rb_is_blank, 0))?;
Ok(())
}