Trait magnus::typed_data::Inspect

source ·
pub trait Inspect {
    // Required method
    fn inspect(&self) -> String;
}
Expand description

Trait for a Ruby-compatible #inspect method.

Automatically implemented for any type implementing Debug.

See also Dup, IsEql, typed_data::Cmp, and typed_data::Hash.

§Examples

use std::fmt;

use magnus::{
    class, define_class, function, gc, method, prelude::*, rb_assert, typed_data,
    value::Opaque, DataTypeFunctions, IntoValue, TypedData, Value,
};

#[derive(TypedData)]
#[magnus(class = "Pair", free_immediately, mark)]
struct Pair {
    #[magnus(opaque_attr_reader)]
    a: Opaque<Value>,
    #[magnus(opaque_attr_reader)]
    b: Opaque<Value>,
}

impl Pair {
    fn new(a: Value, b: Value) -> Self {
        Self {
            a: a.into(),
            b: b.into(),
        }
    }
}

impl DataTypeFunctions for Pair {
    fn mark(&self, marker: &gc::Marker) {
        marker.mark(self.a);
        marker.mark(self.b);
    }
}

impl fmt::Debug for Pair {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Pair")
            .field("a", &self.a())
            .field("b", &self.b())
            .finish()
    }
}

let class = define_class("Pair", class::object()).unwrap();
class
    .define_singleton_method("new", function!(Pair::new, 2))
    .unwrap();
class
    .define_method(
        "inspect",
        method!(<Pair as typed_data::Inspect>::inspect, 0),
    )
    .unwrap();

let pair = Pair::new("foo".into_value(), 1.into_value());
rb_assert!(r#"pair.inspect == "Pair { a: \"foo\", b: 1 }""#, pair);

Required Methods§

source

fn inspect(&self) -> String

Implementors§

source§

impl<T> Inspect for T
where T: Debug,