Trait Extension

Source
pub trait Extension<O = ()> {
    type Implementation: ExtensionType<O>;

    // Required methods
    fn implementation() -> &'static Self::Implementation;
    fn options(self) -> O;

    // Provided method
    fn globals(_globals: &Object<'_>, _options: &O) -> Result<()> { ... }
}
Expand description

A trait for defining an extension with options.

§Example

use rquickjs::{Ctx, JsLifetime, Object, Result};
use rquickjs_extension::{Extension, ModuleImpl};

#[derive(JsLifetime, Debug)]
struct MyExtensionOptions {
    user: String,
}

struct MyExtension {
    options: MyExtensionOptions,
}

impl MyExtension {
    pub fn new<T: Into<String>>(user: T) -> Self {
        Self {
            options: MyExtensionOptions {
                user: user.into(),
            },
        }
    }
}

impl Extension<MyExtensionOptions> for MyExtension {
    type Implementation = ModuleImpl<MyExtensionOptions>;

    fn implementation() -> &'static Self::Implementation {
        &ModuleImpl {
            declare: |decl| {
                decl.declare("user")?;
                Ok(())
            },
            evaluate: |ctx, exports, options| {
                exports.export("user", options.user.clone())?;
                Ok(())
            },
            name: "my-module",
        }
    }

    fn options(self) -> MyExtensionOptions {
        self.options
    }

    fn globals(globals: &Object<'_>, options: &MyExtensionOptions) -> Result<()> {
        globals.set("user", options.user.clone())?;
        Ok(())
    }
}

Required Associated Types§

Source

type Implementation: ExtensionType<O>

Required Methods§

Source

fn implementation() -> &'static Self::Implementation

Source

fn options(self) -> O

Provided Methods§

Source

fn globals(_globals: &Object<'_>, _options: &O) -> Result<()>

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§