[−][src]Macro rosy::def_method
Defines a method on a Class
instance in a simple manner.
This is purely a convenience wrapper for def_method
that makes the
process much less painful and tedious.
Examples
This macro skips all of the necessary type shenanigans when calling the
method on Class
. The focus is instead placed where it should be: on the
method's definition.
ⓘThis code runs with edition 2018
use rosy::prelude::*; let class = Class::string(); rosy::def_method!(class, "blank?", |this| unsafe { let this = String::cast_unchecked(this); this.is_whitespace() }).unwrap(); let string = String::from(" \n\r\t"); let result = string.call("blank?"); assert_eq!(result.unwrap(), true);
All argument counts supported by def_method
work here as well:
ⓘThis code runs with edition 2018
use rosy::prelude::*; let class = Class::object(); rosy::def_method!(class, "eql_either?", |snap, crackle, pop| { snap == crackle || snap == pop }).unwrap(); let object = AnyObject::from("snap"); let result = object.call_with("eql_either?", &[AnyObject::nil(), object]); assert_eq!(result.unwrap(), true);
The same types supported in def_method
are supported here via explicit
type annotations:
ⓘThis code runs with edition 2018
use rosy::prelude::*; let class = Class::array(); rosy::def_method!(class, "plus_args", |this, args: Array| unsafe { Array::cast_unchecked(this).plus(args) }).unwrap(); let expected: &[i32] = &[0, 1, 2, 3, 4, 5, 6]; let array: Array<Integer> = (0..4).collect(); let value = array.call_with("plus_args", &[ Integer::from(4), Integer::from(5), Integer::from(6), ]).unwrap().to_array().unwrap(); assert_eq!(value, *expected);