Trait magnus::module::Module

source ·
pub trait Module: Object + Deref<Target = Value> + ReprValue + Copy {
Show 14 methods // Provided methods fn define_class<T>(self, name: T, superclass: RClass) -> Result<RClass, Error> where T: IntoId { ... } fn define_module<T>(self, name: T) -> Result<RModule, Error> where T: IntoId { ... } fn define_error<T>( self, name: T, superclass: ExceptionClass ) -> Result<ExceptionClass, Error> where T: IntoId { ... } fn include_module(self, module: RModule) -> Result<(), Error> { ... } fn prepend_module(self, module: RModule) -> Result<(), Error> { ... } fn const_set<T, U>(self, name: T, value: U) -> Result<(), Error> where T: IntoId, U: IntoValue { ... } fn const_get<T, U>(self, name: T) -> Result<U, Error> where T: IntoId, U: TryConvert { ... } fn is_inherited<T>(self, other: T) -> bool where T: Deref<Target = Value> + Module { ... } fn ancestors(self) -> RArray { ... } fn define_method<T, M>(self, name: T, func: M) -> Result<(), Error> where T: IntoId, M: Method { ... } fn define_private_method<M>(self, name: &str, func: M) -> Result<(), Error> where M: Method { ... } fn define_protected_method<M>(self, name: &str, func: M) -> Result<(), Error> where M: Method { ... } fn define_attr<T>(self, name: T, rw: Attr) -> Result<(), Error> where T: IntoId { ... } fn define_alias<T, U>(self, dst: T, src: U) -> Result<(), Error> where T: IntoId, U: IntoId { ... }
}
Expand description

Functions available on both classes and modules.

Provided Methods§

source

fn define_class<T>(self, name: T, superclass: RClass) -> Result<RClass, Error>where T: IntoId,

Define a class in self’s scope.

Examples
use magnus::{class, define_module, Module};

let outer = define_module("Outer").unwrap();
let inner = outer.define_class("Inner", class::object()).unwrap();
assert!(inner.is_kind_of(class::class()));
source

fn define_module<T>(self, name: T) -> Result<RModule, Error>where T: IntoId,

Define a module in self’s scope.

Examples
use magnus::{class, define_module, Module};

let outer = define_module("Outer").unwrap();
let inner = outer.define_module("Inner").unwrap();
assert!(inner.is_kind_of(class::module()));
source

fn define_error<T>( self, name: T, superclass: ExceptionClass ) -> Result<ExceptionClass, Error>where T: IntoId,

Define an exception class in self’s scope.

Examples
use magnus::{exception, define_module, Module};

let outer = define_module("Outer").unwrap();
let inner = outer.define_error("InnerError", exception::standard_error()).unwrap();
assert!(inner.is_inherited(exception::standard_error()));
source

fn include_module(self, module: RModule) -> Result<(), Error>

Include module into self.

Effectively makes module the superclass of self. See also prepend_module.

Examples
use magnus::{class, function, Module, RClass, RModule};

fn example() -> i64 {
    42
}

let module = RModule::new();
module.define_method("example", function!(example, 0)).unwrap();

let class = RClass::new(class::object()).unwrap();
class.include_module(module);

let obj = class.new_instance(()).unwrap();
assert_eq!(obj.funcall::<_, _, i64>("example", ()).unwrap(), 42);
source

fn prepend_module(self, module: RModule) -> Result<(), Error>

Prepend self with module.

Similar to include_module, but inserts module as if it were a subclass in the inheritance chain.

Examples
use magnus::{call_super, eval, function, Error, Module, RClass, RModule};

fn super_example() -> i64 {
    40
}

fn example() -> Result<i64, Error> {
    Ok(call_super::<_, i64>(())? + 2)
}

let module = RModule::new();
module.define_method("example", function!(example, 0)).unwrap();

let class: RClass = eval(r#"
    class Example
      def example
        40
      end
    end
    Example
"#).unwrap();
class.prepend_module(module);

let obj = class.new_instance(()).unwrap();
assert_eq!(obj.funcall::<_, _, i64>("example", ()).unwrap(), 42);
source

fn const_set<T, U>(self, name: T, value: U) -> Result<(), Error>where T: IntoId, U: IntoValue,

Set the value for the constant name within self’s scope.

Examples
use magnus::{class, eval, Module, RClass, Value};

class::array().const_set("EXAMPLE", 42).unwrap();

assert_eq!(eval::<i64>("Array::EXAMPLE").unwrap(), 42);
source

fn const_get<T, U>(self, name: T) -> Result<U, Error>where T: IntoId, U: TryConvert,

Get the value for the constant name within self’s scope.

Examples
use magnus::{class, eval, Module, RClass, Value};

eval::<Value>("
    class Example
      VALUE = 42
    end
").unwrap();

let class = class::object().const_get::<_, RClass>("Example").unwrap();
assert_eq!(class.const_get::<_, i64>("VALUE").unwrap(), 42);
source

fn is_inherited<T>(self, other: T) -> boolwhere T: Deref<Target = Value> + Module,

Returns whether or not self inherits from other.

Classes including a module are considered to inherit from that module.

Examples
use magnus::{class, eval, Module, RClass};

let a = RClass::new(class::object()).unwrap();
let b = RClass::new(a).unwrap();
assert!(b.is_inherited(a));
assert!(!a.is_inherited(b));
source

fn ancestors(self) -> RArray

Return the classes and modules self inherits, includes, or prepends.

Examples
use magnus::{class, eval, Module};

let ary = class::string().ancestors();

let res: bool = eval!("ary == [String, Comparable, Object, Kernel, BasicObject]", ary).unwrap();
assert!(res);
source

fn define_method<T, M>(self, name: T, func: M) -> Result<(), Error>where T: IntoId, M: Method,

Define a method in self’s scope.

Examples
use magnus::{class, eval, method, Module};

fn escape_unicode(s: String) -> String {
    s.escape_unicode().to_string()
}

class::string().define_method("escape_unicode", method!(escape_unicode, 0)).unwrap();

let res = eval::<bool>(r#""🤖\etest".escape_unicode == "\\u{1f916}\\u{1b}\\u{74}\\u{65}\\u{73}\\u{74}""#).unwrap();
assert!(res);
Examples found in repository?
examples/point.rs (line 32)
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
fn main() -> Result<(), Error> {
    let _cleanup = unsafe { embed::init() };

    let class = define_class("Point", class::object())?;
    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))?;
    class.define_method("distance", method!(Point::distance, 1))?;

    let d: f64 = eval(
        "a = Point.new(0, 0)
         b = Point.new(5, 10)
         a.distance(b)",
    )?;

    println!("{}", d);
    Ok(())
}
More examples
Hide additional examples
examples/mut_point.rs (line 44)
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
fn main() -> Result<(), Error> {
    let _cleanup = unsafe { embed::init() };

    let class = define_class("Point", class::object())?;
    class.define_singleton_method("new", function!(MutPoint::new, 2))?;
    class.define_method("x", method!(MutPoint::x, 0))?;
    class.define_method("x=", method!(MutPoint::set_x, 1))?;
    class.define_method("y", method!(MutPoint::y, 0))?;
    class.define_method("y=", method!(MutPoint::set_y, 1))?;
    class.define_method("distance", method!(MutPoint::distance, 1))?;

    let d: f64 = eval(
        "a = Point.new(0, 0)
         b = Point.new(0, 0)
         b.x = 5
         b.y = 10
         a.distance(b)",
    )?;

    println!("{}", d);
    Ok(())
}
source

fn define_private_method<M>(self, name: &str, func: M) -> Result<(), Error>where M: Method,

Define a private method in self’s scope.

Examples
use magnus::{class, eval, exception, function, Module, Value};

fn percent_encode(c: char) -> String {
    if c.is_ascii_alphanumeric() || c == '-' || c == '_' || c == '.' || c == '~' {
        String::from(c)
    } else {
        format!("%{:X}", c as u32)
    }
}

class::string().define_private_method("percent_encode_char", function!(percent_encode, 1)).unwrap();

eval::<Value>(r#"
    class String
      def percent_encode
        chars.map {|c| percent_encode_char(c)}.join("")
      end
    end
"#).unwrap();

let res = eval::<bool>(r#""foo bar".percent_encode == "foo%20bar""#).unwrap();
assert!(res);

assert!(eval::<bool>(r#"" ".percent_encode_char(" ")"#).unwrap_err().is_kind_of(exception::no_method_error()));
source

fn define_protected_method<M>(self, name: &str, func: M) -> Result<(), Error>where M: Method,

Define a protected method in self’s scope.

Examples
use magnus::{class, eval, exception, method, Module, Value};

fn escape_unicode(s: String) -> String {
    s.escape_unicode().to_string()
}

fn is_invisible(c: char) -> bool {
    c.is_control() || c.is_whitespace()
}

class::string().define_method("escape_unicode", method!(escape_unicode, 0)).unwrap();
class::string().define_protected_method("invisible?", method!(is_invisible, 0)).unwrap();

eval::<Value>(r#"
    class String
      def escape_invisible
        chars.map {|c| c.invisible? ? c.escape_unicode : c}.join("")
      end
    end
"#).unwrap();

let res: bool = eval!(r#"
    "🤖\tfoo bar".escape_invisible == "🤖\\u{9}foo\\u{20}bar"
"#).unwrap();
assert!(res);

assert!(eval::<bool>(r#"" ".invisible?"#).unwrap_err().is_kind_of(exception::no_method_error()));
source

fn define_attr<T>(self, name: T, rw: Attr) -> Result<(), Error>where T: IntoId,

Define public accessor methods for the attribute name.

name should be without the preceding @.

Examples
use magnus::{class, Attr, Module, RClass, Value};

let class = RClass::new(class::object()).unwrap();
class.define_attr("example", Attr::ReadWrite).unwrap();

let obj = class.new_instance(()).unwrap();
let _: Value = obj.funcall("example=", (42,)).unwrap();
assert_eq!(obj.funcall::<_, _, i64>("example", ()).unwrap(), 42);
source

fn define_alias<T, U>(self, dst: T, src: U) -> Result<(), Error>where T: IntoId, U: IntoId,

Alias the method src of self as dst.

Examples
use magnus::{class, function, Module, RClass};

fn example() -> i64 {
    42
}

let class = RClass::new(class::object()).unwrap();
class.define_method("example", function!(example, 0)).unwrap();
class.define_alias("test", "example").unwrap();

let obj = class.new_instance(()).unwrap();
assert_eq!(obj.funcall::<_, _, i64>("test", ()).unwrap(), 42);

Implementors§