#[init]
Expand description
Mark a function as the ‘init’ function to be run for a library when it is
require
d by Ruby code.
The init function is used to define your Ruby modules & classes, bind functions as Ruby methods, etc.
Attributes
name = "..."
- sets the name of the init function exported for Ruby. This default’s to the current crate’s name. The name will be prepended withInit_
and-
will be replaced with_
. This (minus theInit_
prefix) must match the name of the final.so
/.bundle
file.
Examples
fn distance(a: (f64, f64), b: (f64, f64)) -> f64 {
((b.0 - a.0).powi(2) + (b.1 - a.1).powi(2)).sqrt()
}
#[magnus::init]
fn init() {
magnus::define_global_function("distance", magnus::function!(distance, 2));
}
The init function can also return Result<(), magnus::Error>
.
use magnus::{define_module, function, method, prelude::*, Error};
#[magnus::wrap(class = "Euclid::Point", free_immediately, size)]
struct Point {
x: isize,
y: isize,
}
impl Point {
fn new(x: isize, y: isize) -> Self {
Self { x, y }
}
fn x(&self) -> isize {
self.x
}
fn y(&self) -> isize {
self.y
}
}
#[magnus::init]
fn init() -> Result<(), Error> {
let module = define_module("Euclid")?;
let class = module.define_class("Point", Default::default())?;
class.define_singleton_method("new", function!(Point::new, 2))?;
class.define_method("x", method!(Point::x, 0))?;
class.define_method("y", method!(Point::y, 0))?;
Ok(())
}
Setting the name.
#[magnus::init(name = "example")]
fn init() {
()
}