Trait minijinja::value::Object

source ·
pub trait Object: Display + Debug + Any + Sync + Send {
    fn kind(&self) -> ObjectKind<'_> { ... }
    fn call_method(
        &self,
        state: &State<'_, '_>,
        name: &str,
        args: &[Value]
    ) -> Result<Value, Error> { ... } fn call(&self, state: &State<'_, '_>, args: &[Value]) -> Result<Value, Error> { ... } }
Expand description

A utility trait that represents a dynamic object.

The engine uses the Value type to represent values that the engine knows about. Most of these values are primitives such as integers, strings or maps. However it is also possible to expose custom types without undergoing a serialization step to the engine. For this to work a type needs to implement the Object trait and be wrapped in a value with Value::from_object. The ownership of the object will then move into the value type. The engine uses reference counted objects with interior mutability in the value type. This means that all trait methods take &self and types like Mutex need to be used to enable mutability. Objects need to implement Display which is used by the engine to convert the object into a string if needed. Additionally Debug is required as well.

The exact runtime characteristics of the object are influenced by the kind of the object. By default an object can just be stringified and methods can be called.

For examples of how to implement objects refer to SeqObject and StructObject.

Provided Methods§

Describes the kind of an object.

If not implemented behavior for an object is ObjectKind::Plain which just means that it’s stringifyable and potentially can be called or has methods.

For more information see ObjectKind.

Called when the engine tries to call a method on the object.

It’s the responsibility of the implementer to ensure that an error is generated if an invalid method is invoked.

To convert the arguments into arguments use the from_args function.

Called when the object is invoked directly.

The default implementation just generates an error that the object cannot be invoked.

To convert the arguments into arguments use the from_args function.

Implementations§

Returns some reference to the boxed object if it is of type T, or None if it isn’t.

This is basically the “reverse” of from_object.

Example
use std::fmt;

#[derive(Debug)]
struct Thing {
    id: usize,
}

impl fmt::Display for Thing {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self, f)
    }
}

impl Object for Thing {}

let x_value = Value::from_object(Thing { id: 42 });
let value_as_obj = x_value.as_object().unwrap();
let thing = value_as_obj.downcast_ref::<Thing>().unwrap();
assert_eq!(thing.id, 42);

Checks if the object is of a specific type.

Implementations on Foreign Types§

Implementors§