pub struct Ruby(/* private fields */);
Expand description
A handle to access Ruby’s API.
Using Ruby’s API requires the Ruby VM to be initialised and all access to be from a Ruby-created thread.
This structure allows safe access to Ruby’s API as it should only be possible to acquire an instance in situations where Ruby’s API is known to be available.
Many functions that take Ruby values as arguments are available directly
without having to use a Ruby
handle, as being able to provide a Ruby
value is ‘proof’ the function is being called from a Ruby thread. Because
of this most methods defined on Ruby
deal with creating Ruby objects
from Rust data.
The methods available on Ruby
are broken up into sections for easier
navigation.
- Accessing
Ruby
- how to get aRuby
handle - Argument Parsing - helpers for argument handling
- Blocks - working with Ruby blocks
- Conversion to
Value
- Core Classes - access built-in classes
- Core Exceptions - access built-in exceptions
- Core Modules - access built-in modules
- Embedding - functions relevant when embedding Ruby in Rust
Encoding
- string encoding- Encoding Index - string encoding
- Errors
- Extracting values from
Opaque
/Lazy
false
Fiber
Fixnum
- small/fast integersFloat
Flonum
- lower precision/fast floatsGC
- Garbage Collection- Globals - global variables, etc, plus current VM state such
as calling the current
super
method. Id
- low-level Symbol representationIo
- IO helper functionsInteger
Mutex
nil
Proc
- Ruby’s blocks as objectsProcess
- external processesRange
RArray
RbEncoding
- string encodingRBignum
- big integersRFloat
RHash
RModule
RRational
RRegexp
RString
RTypedData
- wrapping Rust data in a Ruby objectStaticSymbol
- non GC’d symbolsStruct
Symbol
Thread
Time
true
typed_data::Obj
- wrapping Rust data in a Ruby object
Implementations§
Source§impl Ruby
§Accessing Ruby
These functions allow you to obtain a Ruby
handle only when the current
thread is a Ruby thread.
impl Ruby
§Accessing Ruby
These functions allow you to obtain a Ruby
handle only when the current
thread is a Ruby thread.
Methods exposed to Ruby via the method
,
function
or init
macros
can also take an optional first argument of &Ruby
to obtain a Ruby
handle.
Sourcepub fn get() -> Result<Self, RubyUnavailableError>
pub fn get() -> Result<Self, RubyUnavailableError>
Get a handle to Ruby’s API.
Returns a new handle to Ruby’s API if it can be verified the current thread is a Ruby thread.
If the Ruby API is not useable, returns Err(RubyUnavailableError)
.
Sourcepub fn get_with<T>(value: T) -> Selfwhere
T: ReprValue,
pub fn get_with<T>(value: T) -> Selfwhere
T: ReprValue,
Get a handle to Ruby’s API.
Returns a new handle to Ruby’s API using a Ruby value as proof that the current thread is a Ruby thread.
Note that all Ruby values are Copy
, so this will not take ownership
of the passed value.
Sourcepub unsafe fn get_unchecked() -> Self
pub unsafe fn get_unchecked() -> Self
Get a handle to Ruby’s API.
§Safety
This must only be called from a Ruby thread - that is one created by
Ruby, or the main thread after embed::init
has
been called - and without having released the GVL.
Source§impl Ruby
impl Ruby
See also the Proc
type.
Sourcepub fn proc_new<R>(&self, block: fn(&Ruby, &[Value], Option<Proc>) -> R) -> Procwhere
R: BlockReturn,
pub fn proc_new<R>(&self, block: fn(&Ruby, &[Value], Option<Proc>) -> R) -> Procwhere
R: BlockReturn,
Create a new Proc
.
As block
is a function pointer, only functions and closures that do
not capture any variables are permitted. For more flexibility (at the
cost of allocating) see proc_from_fn
.
§Examples
use magnus::{prelude::*, rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let proc = ruby.proc_new(|_ruby, args, _block| {
let acc = i64::try_convert(*args.get(0).unwrap())?;
let i = i64::try_convert(*args.get(1).unwrap())?;
Ok(acc + i)
});
rb_assert!(ruby, "proc.call(1, 2) == 3", proc);
rb_assert!(ruby, "[1, 2, 3, 4, 5].inject(&proc) == 15", proc);
Ok(())
}
Sourcepub fn proc_from_fn<F, R>(&self, block: F) -> Proc
pub fn proc_from_fn<F, R>(&self, block: F) -> Proc
Create a new Proc
.
See also proc_new
, which is more efficient when
block
is a function or closure that does not capture any variables.
§Examples
use magnus::{prelude::*, rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let mut count = 0;
let proc = ruby.proc_from_fn(move |_ruby, args, _block| {
let step = i64::try_convert(*args.get(0).unwrap())?;
count += step;
Ok(count)
});
rb_assert!(ruby, "proc.call(1) == 1", proc);
rb_assert!(ruby, "proc.call(1) == 2", proc);
rb_assert!(ruby, "proc.call(2) == 4", proc);
Ok(())
}
Source§impl Ruby
§Blocks
Functions to enable working with Ruby blocks.
impl Ruby
§Blocks
Functions to enable working with Ruby blocks.
See also the block
module.
Sourcepub fn block_given(&self) -> bool
pub fn block_given(&self) -> bool
Returns whether a Ruby block has been supplied to the current method.
§Examples
use magnus::{function, rb_assert, Error, Ruby};
fn got_block(ruby: &Ruby) -> bool {
ruby.block_given()
}
fn example(ruby: &Ruby) -> Result<(), Error> {
ruby.define_global_function("got_block?", function!(got_block, 0));
rb_assert!(ruby, "got_block? {} == true");
rb_assert!(ruby, "got_block? == false");
Ok(())
}
Sourcepub fn block_proc(&self) -> Result<Proc, Error>
pub fn block_proc(&self) -> Result<Proc, Error>
Returns the block given to the current method as a Proc
instance.
§Examples
use magnus::{block::Proc, function, rb_assert, Error, Ruby};
fn make_proc(ruby: &Ruby) -> Result<Proc, Error> {
ruby.block_proc()
}
fn example(ruby: &Ruby) -> Result<(), Error> {
ruby.define_global_function("make_proc", function!(make_proc, 0));
rb_assert!(ruby, "make_proc {}.is_a?(Proc)");
Ok(())
}
Sourcepub fn yield_value<T, U>(&self, val: T) -> Result<U, Error>where
T: IntoValue,
U: TryConvert,
pub fn yield_value<T, U>(&self, val: T) -> Result<U, Error>where
T: IntoValue,
U: TryConvert,
Yields a value to the block given to the current method.
Note: A method using yield_value
converted to an Enumerator with
to_enum
/Value::enumeratorize
will result in a non-functional
Enumerator on versions of Ruby before 3.1. See Yield
for an
alternative.
§Examples
use magnus::{function, rb_assert, Error, Ruby, Value};
fn metasyntactic_variables(ruby: &Ruby) -> Result<(), Error> {
let _: Value = ruby.yield_value("foo")?;
let _: Value = ruby.yield_value("bar")?;
let _: Value = ruby.yield_value("baz")?;
Ok(())
}
fn example(ruby: &Ruby) -> Result<(), Error> {
ruby.define_global_function(
"metasyntactic_variables",
function!(metasyntactic_variables, 0),
);
let vars = ruby.ary_new();
rb_assert!(
ruby,
"metasyntactic_variables {|var| vars << var} == nil",
vars
);
rb_assert!(ruby, r#"vars == ["foo", "bar", "baz"]"#, vars);
Ok(())
}
Sourcepub fn yield_values<T, U>(&self, vals: T) -> Result<U, Error>where
T: ArgList,
U: TryConvert,
pub fn yield_values<T, U>(&self, vals: T) -> Result<U, Error>where
T: ArgList,
U: TryConvert,
Yields multiple values to the block given to the current method.
Note: A method using yield_values
converted to an Enumerator with
to_enum
/Value::enumeratorize
will result in a non-functional
Enumerator on versions of Ruby before 3.1. See YieldValues
for an
alternative.
§Examples
use magnus::{function, kwargs, rb_assert, Error, Ruby, Value};
fn metasyntactic_variables(ruby: &Ruby) -> Result<(), Error> {
let _: Value = ruby.yield_values((0, kwargs!("var" => "foo")))?;
let _: Value = ruby.yield_values((1, kwargs!("var" => "bar")))?;
let _: Value = ruby.yield_values((2, kwargs!("var" => "baz")))?;
Ok(())
}
fn example(ruby: &Ruby) -> Result<(), Error> {
ruby.define_global_function(
"metasyntactic_variables",
function!(metasyntactic_variables, 0),
);
let vars = ruby.ary_new();
rb_assert!(
ruby,
"metasyntactic_variables {|pos, var:| vars << [pos, var]} == nil",
vars
);
rb_assert!(
ruby,
r#"vars == [[0, "foo"], [1, "bar"], [2, "baz"]]"#,
vars
);
Ok(())
}
Sourcepub fn yield_splat<T>(&self, vals: RArray) -> Result<T, Error>where
T: TryConvert,
pub fn yield_splat<T>(&self, vals: RArray) -> Result<T, Error>where
T: TryConvert,
Yields a Ruby Array to the block given to the current method.
Note: A method using yield_splat
converted to an Enumerator with
to_enum
/Value::enumeratorize
will result in a non-functional
Enumerator on versions of Ruby before 3.1. See YieldSplat
for an
alternative.
§Examples
use magnus::{function, rb_assert, Error, Ruby, Value};
fn metasyntactic_variables(ruby: &Ruby) -> Result<(), Error> {
let ary = ruby.ary_new();
ary.push(0)?;
ary.push("foo")?;
let _: Value = ruby.yield_splat(ary)?;
let ary = ruby.ary_new();
ary.push(1)?;
ary.push("bar")?;
let _: Value = ruby.yield_splat(ary)?;
let ary = ruby.ary_new();
ary.push(2)?;
ary.push("baz")?;
let _: Value = ruby.yield_splat(ary)?;
Ok(())
}
fn example(ruby: &Ruby) -> Result<(), Error> {
ruby.define_global_function(
"metasyntactic_variables",
function!(metasyntactic_variables, 0),
);
let vars = ruby.ary_new();
rb_assert!(
ruby,
"metasyntactic_variables {|pos, var| vars << [pos, var]} == nil",
vars
);
rb_assert!(
ruby,
r#"vars == [[0, "foo"], [1, "bar"], [2, "baz"]]"#,
vars
);
Ok(())
}
Source§impl Ruby
§Core Classes
Functions to access Ruby’s built-in classes.
impl Ruby
§Core Classes
Functions to access Ruby’s built-in classes.
See also the class
module.
Sourcepub fn class_array(&self) -> RClass
pub fn class_array(&self) -> RClass
Return Ruby’s Array
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Array", klass = ruby.class_array());
Ok(())
}
Sourcepub fn class_basic_object(&self) -> RClass
pub fn class_basic_object(&self) -> RClass
Return Ruby’s BasicObject
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == BasicObject",
klass = ruby.class_basic_object()
);
Ok(())
}
Sourcepub fn class_binding(&self) -> RClass
pub fn class_binding(&self) -> RClass
Return Ruby’s Binding
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Binding", klass = ruby.class_binding());
Ok(())
}
Sourcepub fn class_class(&self) -> RClass
pub fn class_class(&self) -> RClass
Return Ruby’s Class
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Class", klass = ruby.class_class());
Ok(())
}
Sourcepub fn class_complex(&self) -> RClass
pub fn class_complex(&self) -> RClass
Return Ruby’s Complex
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Complex", klass = ruby.class_complex());
Ok(())
}
Sourcepub fn class_dir(&self) -> RClass
pub fn class_dir(&self) -> RClass
Return Ruby’s Dir
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Dir", klass = ruby.class_dir());
Ok(())
}
Sourcepub fn class_encoding(&self) -> RClass
pub fn class_encoding(&self) -> RClass
Return Ruby’s Encoding
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Encoding", klass = ruby.class_encoding());
Ok(())
}
Sourcepub fn class_enumerator(&self) -> RClass
pub fn class_enumerator(&self) -> RClass
Return Ruby’s Enumerator
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Enumerator", klass = ruby.class_enumerator());
Ok(())
}
Sourcepub fn class_false_class(&self) -> RClass
pub fn class_false_class(&self) -> RClass
Return Ruby’s FalseClass
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == FalseClass",
klass = ruby.class_false_class()
);
Ok(())
}
Sourcepub fn class_file(&self) -> RClass
pub fn class_file(&self) -> RClass
Return Ruby’s File
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == File", klass = ruby.class_file());
Ok(())
}
Sourcepub fn class_float(&self) -> RClass
pub fn class_float(&self) -> RClass
Return Ruby’s Float
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Float", klass = ruby.class_float());
Ok(())
}
Sourcepub fn class_hash(&self) -> RClass
pub fn class_hash(&self) -> RClass
Return Ruby’s Hash
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Hash", klass = ruby.class_hash());
Ok(())
}
Sourcepub fn class_io(&self) -> RClass
pub fn class_io(&self) -> RClass
Return Ruby’s IO
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == IO", klass = ruby.class_io());
Ok(())
}
Sourcepub fn class_integer(&self) -> RClass
pub fn class_integer(&self) -> RClass
Return Ruby’s Integer
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Integer", klass = ruby.class_integer());
Ok(())
}
Sourcepub fn class_match(&self) -> RClass
pub fn class_match(&self) -> RClass
Return Ruby’s MatchData
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == MatchData", klass = ruby.class_match());
Ok(())
}
Sourcepub fn class_method(&self) -> RClass
pub fn class_method(&self) -> RClass
Return Ruby’s Method
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Method", klass = ruby.class_method());
Ok(())
}
Sourcepub fn class_module(&self) -> RClass
pub fn class_module(&self) -> RClass
Return Ruby’s Module
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Module", klass = ruby.class_module());
Ok(())
}
Sourcepub fn class_name_error_mesg(&self) -> RClass
pub fn class_name_error_mesg(&self) -> RClass
Return Ruby’s NameError::message
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
r#"klass.name == "NameError::message""#,
klass = ruby.class_name_error_mesg()
);
Ok(())
}
Sourcepub fn class_nil_class(&self) -> RClass
pub fn class_nil_class(&self) -> RClass
Return Ruby’s NilClass
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == NilClass", klass = ruby.class_nil_class());
Ok(())
}
Sourcepub fn class_numeric(&self) -> RClass
pub fn class_numeric(&self) -> RClass
Return Ruby’s Numeric
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Numeric", klass = ruby.class_numeric());
Ok(())
}
Sourcepub fn class_object(&self) -> RClass
pub fn class_object(&self) -> RClass
Return Ruby’s Object
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Object", klass = ruby.class_object());
Ok(())
}
Sourcepub fn class_proc(&self) -> RClass
pub fn class_proc(&self) -> RClass
Return Ruby’s Proc
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Proc", klass = ruby.class_proc());
Ok(())
}
Sourcepub fn class_random(&self) -> RClass
pub fn class_random(&self) -> RClass
Return Ruby’s Random
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Random", klass = ruby.class_random());
Ok(())
}
Sourcepub fn class_range(&self) -> RClass
pub fn class_range(&self) -> RClass
Return Ruby’s Range
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Range", klass = ruby.class_range());
Ok(())
}
Sourcepub fn class_rational(&self) -> RClass
pub fn class_rational(&self) -> RClass
Return Ruby’s Rational
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Rational", klass = ruby.class_rational());
Ok(())
}
Sourcepub fn class_refinement(&self) -> RClass
Available on ruby_gte_3_1
only.
pub fn class_refinement(&self) -> RClass
ruby_gte_3_1
only.Return Ruby’s Refinement
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Refinement", klass = ruby.class_refinement());
Ok(())
}
Sourcepub fn class_regexp(&self) -> RClass
pub fn class_regexp(&self) -> RClass
Return Ruby’s Regexp
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Regexp", klass = ruby.class_regexp());
Ok(())
}
Sourcepub fn class_stat(&self) -> RClass
pub fn class_stat(&self) -> RClass
Return Ruby’s File::Stat
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == File::Stat", klass = ruby.class_stat());
Ok(())
}
Sourcepub fn class_string(&self) -> RClass
pub fn class_string(&self) -> RClass
Return Ruby’s String
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == String", klass = ruby.class_string());
Ok(())
}
Sourcepub fn class_struct(&self) -> RClass
pub fn class_struct(&self) -> RClass
Return Ruby’s Struct
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Struct", klass = ruby.class_struct());
Ok(())
}
Sourcepub fn class_symbol(&self) -> RClass
pub fn class_symbol(&self) -> RClass
Return Ruby’s Symbol
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Symbol", klass = ruby.class_symbol());
Ok(())
}
Sourcepub fn class_thread(&self) -> RClass
pub fn class_thread(&self) -> RClass
Return Ruby’s Thread
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Thread", klass = ruby.class_thread());
Ok(())
}
Sourcepub fn class_time(&self) -> RClass
pub fn class_time(&self) -> RClass
Return Ruby’s Time
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == Time", klass = ruby.class_time());
Ok(())
}
Sourcepub fn class_true_class(&self) -> RClass
pub fn class_true_class(&self) -> RClass
Return Ruby’s TrueClass
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == TrueClass", klass = ruby.class_true_class());
Ok(())
}
Sourcepub fn class_unbound_method(&self) -> RClass
pub fn class_unbound_method(&self) -> RClass
Return Ruby’s UnboundMethod
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == UnboundMethod",
klass = ruby.class_unbound_method()
);
Ok(())
}
Source§impl Ruby
§Embedding
Functions relevant when embedding Ruby in Rust.
impl Ruby
§Embedding
Functions relevant when embedding Ruby in Rust.
See also the embed
module.
Sourcepub fn init(func: fn(&Ruby) -> Result<(), Error>) -> Result<(), String>
Available on crate feature embed
only.
pub fn init(func: fn(&Ruby) -> Result<(), Error>) -> Result<(), String>
embed
only.Initialises the Ruby VM.
Calling this function is only required when embedding Ruby in Rust. It is not required when embedding Rust in Ruby, e.g. in a Ruby Gem.
The Ruby VM can only be initialised once per process, and the Ruby VM cleanup will be run once the passed function has completed.
§Safety
This function takes a function pointer, rather than a closure, so that
it is hard to leak Ruby values that could be used after the Ruby VM has
finished. It is still possible to leak Ruby values with, for example,
a static
with interior mutability. Do not do this.
§Panics
Panics if this, init
, or setup
are collectively called more
than once.
§Examples
magnus::Ruby::init(|ruby| {
let result: i64 = ruby.eval("2 + 2")?;
assert_eq!(result, 4);
Ok(())
})
.unwrap()
Sourcepub fn script<T>(&self, name: T)where
T: IntoRString,
Available on crate feature embed
only.
pub fn script<T>(&self, name: T)where
T: IntoRString,
embed
only.Sets the current script name.
Source§impl Ruby
§Encoding
Functions to access pre-defined Encodings.
impl Ruby
§Encoding
Functions to access pre-defined Encodings.
See also the Encoding
type.
Sourcepub fn enc_default_external(&self) -> Encoding
pub fn enc_default_external(&self) -> Encoding
Returns the default internal encoding as a Ruby object.
This is the encoding used for anything out-of-process, such as reading from files or sockets.
Sourcepub fn enc_default_internal(&self) -> Option<Encoding>
pub fn enc_default_internal(&self) -> Option<Encoding>
Returns the default external encoding as a Ruby object.
If set, any out-of-process data is transcoded from the default external encoding to the default internal encoding.
Source§impl Ruby
§RbEncoding
Functions to access pre-defined encodings.
impl Ruby
§RbEncoding
Functions to access pre-defined encodings.
See also the RbEncoding
type.
Sourcepub fn ascii8bit_encoding(&self) -> RbEncoding
pub fn ascii8bit_encoding(&self) -> RbEncoding
Returns the encoding that represents ASCII-8BIT a.k.a. binary.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
assert_eq!(ruby.ascii8bit_encoding().name(), "ASCII-8BIT");
Ok(())
}
Sourcepub fn utf8_encoding(&self) -> RbEncoding
pub fn utf8_encoding(&self) -> RbEncoding
Returns the encoding that represents UTF-8.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
assert_eq!(ruby.utf8_encoding().name(), "UTF-8");
Ok(())
}
Sourcepub fn usascii_encoding(&self) -> RbEncoding
pub fn usascii_encoding(&self) -> RbEncoding
Returns the encoding that represents US-ASCII.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
assert_eq!(ruby.usascii_encoding().name(), "US-ASCII");
Ok(())
}
Sourcepub fn locale_encoding(&self) -> RbEncoding
pub fn locale_encoding(&self) -> RbEncoding
Returns the encoding that represents the process’ current locale.
This is dynamic. If you change the process’ locale that should also change the return value of this function.
Sourcepub fn filesystem_encoding(&self) -> RbEncoding
pub fn filesystem_encoding(&self) -> RbEncoding
Returns the filesystem encoding.
This is the encoding that Ruby expects data from the OS’ file system to be encoded as, such as directory names.
Sourcepub fn default_external_encoding(&self) -> RbEncoding
pub fn default_external_encoding(&self) -> RbEncoding
Returns the default external encoding.
This is the encoding used for anything out-of-process, such as reading from files or sockets.
Sourcepub fn default_internal_encoding(&self) -> Option<RbEncoding>
pub fn default_internal_encoding(&self) -> Option<RbEncoding>
Returns the default internal encoding.
If set, any out-of-process data is transcoded from the default external encoding to the default internal encoding.
Sourcepub fn find_encoding(&self, name: &str) -> Option<RbEncoding>
pub fn find_encoding(&self, name: &str) -> Option<RbEncoding>
Returns the encoding with the name or alias name
.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
assert_eq!(ruby.find_encoding("BINARY").unwrap().name(), "ASCII-8BIT");
assert_eq!(ruby.find_encoding("UTF-8").unwrap().name(), "UTF-8");
Ok(())
}
Source§impl Ruby
§Encoding Index
Functions to access pre-defined encodings.
impl Ruby
§Encoding Index
Functions to access pre-defined encodings.
See also the encoding::Index
type.
Sourcepub fn ascii8bit_encindex(&self) -> Index
pub fn ascii8bit_encindex(&self) -> Index
Returns the index for ASCII-8BIT a.k.a. binary.
Sourcepub fn utf8_encindex(&self) -> Index
pub fn utf8_encindex(&self) -> Index
Returns the index for UTF-8.
Sourcepub fn usascii_encindex(&self) -> Index
pub fn usascii_encindex(&self) -> Index
Returns the index for US-ASCII.
Sourcepub fn locale_encindex(&self) -> Index
pub fn locale_encindex(&self) -> Index
Returns the index for the process’ current locale encoding.
This is dynamic. If you change the process’ locale that should also change the return value of this function.
Sourcepub fn filesystem_encindex(&self) -> Index
pub fn filesystem_encindex(&self) -> Index
Returns the index for filesystem encoding.
This is the encoding that Ruby expects data from the OS’ file system to be encoded as, such as directory names.
Sourcepub fn find_encindex(&self, name: &str) -> Result<Index, Error>
pub fn find_encindex(&self, name: &str) -> Result<Index, Error>
Returns the index for the encoding with the name or alias name
.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
assert!(ruby.find_encindex("UTF-8").is_ok());
assert!(ruby.find_encindex("BINARY").is_ok());
assert!(ruby.find_encindex("none").is_err());
Ok(())
}
Source§impl Ruby
impl Ruby
Sourcepub fn iter_break_value<T>(&self, val: T) -> Errorwhere
T: IntoValue,
pub fn iter_break_value<T>(&self, val: T) -> Errorwhere
T: IntoValue,
Create a new error that will break from a loop when returned to Ruby.
§Examples
use magnus::{prelude::*, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let i: i64 =
ruby.range_new(1, 100, false)?
.block_call("each", (), |ruby, args, _block| {
let i = i64::try_convert(*args.get(0).unwrap())?;
if i % 3 == 0 && i % 5 == 0 {
Err(ruby.iter_break_value(i))
} else {
Ok(())
}
})?;
assert_eq!(i, 15);
Ok(())
}
Source§impl Ruby
§Core Exceptions
Functions to access Ruby’s built-in exception classes.
impl Ruby
§Core Exceptions
Functions to access Ruby’s built-in exception classes.
See also the exception
module.
Sourcepub fn exception_arg_error(&self) -> ExceptionClass
pub fn exception_arg_error(&self) -> ExceptionClass
Return Ruby’s ArgumentError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == ArgumentError",
klass = ruby.exception_arg_error()
);
Ok(())
}
Sourcepub fn exception_eof_error(&self) -> ExceptionClass
pub fn exception_eof_error(&self) -> ExceptionClass
Return Ruby’s EOFError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == EOFError",
klass = ruby.exception_eof_error()
);
Ok(())
}
Sourcepub fn exception_enc_compat_error(&self) -> ExceptionClass
pub fn exception_enc_compat_error(&self) -> ExceptionClass
Return Ruby’s Encoding::CompatibilityError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == Encoding::CompatibilityError",
klass = ruby.exception_enc_compat_error()
);
Ok(())
}
Sourcepub fn exception_encoding_error(&self) -> ExceptionClass
pub fn exception_encoding_error(&self) -> ExceptionClass
Return Ruby’s EncodingError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == EncodingError",
klass = ruby.exception_encoding_error()
);
Ok(())
}
Sourcepub fn exception_exception(&self) -> ExceptionClass
pub fn exception_exception(&self) -> ExceptionClass
Return Ruby’s Exception
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == Exception",
klass = ruby.exception_exception()
);
Ok(())
}
Sourcepub fn exception_fatal(&self) -> ExceptionClass
pub fn exception_fatal(&self) -> ExceptionClass
Return Ruby’s fatal
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
r#"klass.name == "fatal""#,
klass = ruby.exception_fatal()
);
Ok(())
}
Sourcepub fn exception_float_domain_error(&self) -> ExceptionClass
pub fn exception_float_domain_error(&self) -> ExceptionClass
Return Ruby’s FloatDomainError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == FloatDomainError",
klass = ruby.exception_float_domain_error()
);
Ok(())
}
Sourcepub fn exception_frozen_error(&self) -> ExceptionClass
pub fn exception_frozen_error(&self) -> ExceptionClass
Return Ruby’s FrozenError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == FrozenError",
klass = ruby.exception_frozen_error()
);
Ok(())
}
Sourcepub fn exception_io_error(&self) -> ExceptionClass
pub fn exception_io_error(&self) -> ExceptionClass
Return Ruby’s IOError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "klass == IOError", klass = ruby.exception_io_error());
Ok(())
}
Sourcepub fn exception_index_error(&self) -> ExceptionClass
pub fn exception_index_error(&self) -> ExceptionClass
Return Ruby’s IndexError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == IndexError",
klass = ruby.exception_index_error()
);
Ok(())
}
Sourcepub fn exception_interrupt(&self) -> ExceptionClass
pub fn exception_interrupt(&self) -> ExceptionClass
Return Ruby’s Interrupt
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == Interrupt",
klass = ruby.exception_interrupt()
);
Ok(())
}
Sourcepub fn exception_key_error(&self) -> ExceptionClass
pub fn exception_key_error(&self) -> ExceptionClass
Return Ruby’s KeyError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == KeyError",
klass = ruby.exception_key_error()
);
Ok(())
}
Sourcepub fn exception_load_error(&self) -> ExceptionClass
pub fn exception_load_error(&self) -> ExceptionClass
Return Ruby’s LoadError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == LoadError",
klass = ruby.exception_load_error()
);
Ok(())
}
Sourcepub fn exception_local_jump_error(&self) -> ExceptionClass
pub fn exception_local_jump_error(&self) -> ExceptionClass
Return Ruby’s LocalJumpError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == LocalJumpError",
klass = ruby.exception_local_jump_error()
);
Ok(())
}
Sourcepub fn exception_math_domain_error(&self) -> ExceptionClass
pub fn exception_math_domain_error(&self) -> ExceptionClass
Return Ruby’s Math::DomainError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == Math::DomainError",
klass = ruby.exception_math_domain_error()
);
Ok(())
}
Sourcepub fn exception_name_error(&self) -> ExceptionClass
pub fn exception_name_error(&self) -> ExceptionClass
Return Ruby’s NameError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == NameError",
klass = ruby.exception_name_error()
);
Ok(())
}
Sourcepub fn exception_no_matching_pattern_error(&self) -> ExceptionClass
pub fn exception_no_matching_pattern_error(&self) -> ExceptionClass
Return Ruby’s NoMatchingPatternError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == NoMatchingPatternError",
klass = ruby.exception_no_matching_pattern_error()
);
Ok(())
}
Sourcepub fn exception_no_matching_pattern_key_error(&self) -> ExceptionClass
Available on ruby_gte_3_1
only.
pub fn exception_no_matching_pattern_key_error(&self) -> ExceptionClass
ruby_gte_3_1
only.Return Ruby’s NoMatchingPatternKeyError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == NoMatchingPatternKeyError",
klass = ruby.exception_no_matching_pattern_key_error()
);
Ok(())
}
Sourcepub fn exception_no_mem_error(&self) -> ExceptionClass
pub fn exception_no_mem_error(&self) -> ExceptionClass
Return Ruby’s NoMemoryError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == NoMemoryError",
klass = ruby.exception_no_mem_error()
);
Ok(())
}
Sourcepub fn exception_no_method_error(&self) -> ExceptionClass
pub fn exception_no_method_error(&self) -> ExceptionClass
Return Ruby’s NoMethodError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == NoMethodError",
klass = ruby.exception_no_method_error()
);
Ok(())
}
Sourcepub fn exception_not_imp_error(&self) -> ExceptionClass
pub fn exception_not_imp_error(&self) -> ExceptionClass
Return Ruby’s NotImplementedError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == NotImplementedError",
klass = ruby.exception_not_imp_error()
);
Ok(())
}
Sourcepub fn exception_range_error(&self) -> ExceptionClass
pub fn exception_range_error(&self) -> ExceptionClass
Return Ruby’s RangeError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == RangeError",
klass = ruby.exception_range_error()
);
Ok(())
}
Sourcepub fn exception_regexp_error(&self) -> ExceptionClass
pub fn exception_regexp_error(&self) -> ExceptionClass
Return Ruby’s RegexpError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == RegexpError",
klass = ruby.exception_regexp_error()
);
Ok(())
}
Sourcepub fn exception_runtime_error(&self) -> ExceptionClass
pub fn exception_runtime_error(&self) -> ExceptionClass
Return Ruby’s RuntimeError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == RuntimeError",
klass = ruby.exception_runtime_error()
);
Ok(())
}
Sourcepub fn exception_script_error(&self) -> ExceptionClass
pub fn exception_script_error(&self) -> ExceptionClass
Return Ruby’s ScriptError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == ScriptError",
klass = ruby.exception_script_error()
);
Ok(())
}
Sourcepub fn exception_security_error(&self) -> ExceptionClass
pub fn exception_security_error(&self) -> ExceptionClass
Return Ruby’s SecurityError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == SecurityError",
klass = ruby.exception_security_error()
);
Ok(())
}
Sourcepub fn exception_signal(&self) -> ExceptionClass
pub fn exception_signal(&self) -> ExceptionClass
Return Ruby’s SignalException
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == SignalException",
klass = ruby.exception_signal()
);
Ok(())
}
Sourcepub fn exception_standard_error(&self) -> ExceptionClass
pub fn exception_standard_error(&self) -> ExceptionClass
Return Ruby’s StandardError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == StandardError",
klass = ruby.exception_standard_error()
);
Ok(())
}
Sourcepub fn exception_stop_iteration(&self) -> ExceptionClass
pub fn exception_stop_iteration(&self) -> ExceptionClass
Return Ruby’s StopIteration
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == StopIteration",
klass = ruby.exception_stop_iteration()
);
Ok(())
}
Sourcepub fn exception_syntax_error(&self) -> ExceptionClass
pub fn exception_syntax_error(&self) -> ExceptionClass
Return Ruby’s SyntaxError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == SyntaxError",
klass = ruby.exception_syntax_error()
);
Ok(())
}
Sourcepub fn exception_sys_stack_error(&self) -> ExceptionClass
pub fn exception_sys_stack_error(&self) -> ExceptionClass
Return Ruby’s SystemStackError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == SystemStackError",
klass = ruby.exception_sys_stack_error()
);
Ok(())
}
Sourcepub fn exception_system_call_error(&self) -> ExceptionClass
pub fn exception_system_call_error(&self) -> ExceptionClass
Return Ruby’s SystemCallError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == SystemCallError",
klass = ruby.exception_system_call_error()
);
Ok(())
}
Sourcepub fn exception_system_exit(&self) -> ExceptionClass
pub fn exception_system_exit(&self) -> ExceptionClass
Return Ruby’s SystemExit
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == SystemExit",
klass = ruby.exception_system_exit()
);
Ok(())
}
Sourcepub fn exception_thread_error(&self) -> ExceptionClass
pub fn exception_thread_error(&self) -> ExceptionClass
Return Ruby’s ThreadError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == ThreadError",
klass = ruby.exception_thread_error()
);
Ok(())
}
Sourcepub fn exception_type_error(&self) -> ExceptionClass
pub fn exception_type_error(&self) -> ExceptionClass
Return Ruby’s TypeError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == TypeError",
klass = ruby.exception_type_error()
);
Ok(())
}
Sourcepub fn exception_zero_div_error(&self) -> ExceptionClass
pub fn exception_zero_div_error(&self) -> ExceptionClass
Return Ruby’s ZeroDivisionError
class.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"klass == ZeroDivisionError",
klass = ruby.exception_zero_div_error()
);
Ok(())
}
Source§impl Ruby
§Fiber
Functions to create and work with Ruby Fiber
s.
impl Ruby
§Fiber
Functions to create and work with Ruby Fiber
s.
See also the Fiber
type.
Sourcepub fn fiber_new<R>(
&self,
storage: Storage,
func: fn(&Ruby, &[Value], Option<Proc>) -> R,
) -> Result<Fiber, Error>where
R: BlockReturn,
Available on ruby_gte_3_1
only.
pub fn fiber_new<R>(
&self,
storage: Storage,
func: fn(&Ruby, &[Value], Option<Proc>) -> R,
) -> Result<Fiber, Error>where
R: BlockReturn,
ruby_gte_3_1
only.Create a Ruby Fiber.
As func
is a function pointer, only functions and closures that do
not capture any variables are permitted. For more flexibility (at the
cost of allocating) see fiber_new_from_fn
.
§Examples
use magnus::{prelude::*, rb_assert, Error, Ruby, Value};
fn example(ruby: &Ruby) -> Result<(), Error> {
let fib = ruby.fiber_new(Default::default(), |ruby, args, _block| {
let mut a = u64::try_convert(*args.get(0).unwrap())?;
let mut b = u64::try_convert(*args.get(1).unwrap())?;
while let Some(c) = a.checked_add(b) {
let _: Value = ruby.fiber_yield((c,))?;
a = b;
b = c;
}
Ok(())
})?;
rb_assert!(ruby, "fib.resume(0, 1) == 1", fib);
rb_assert!(ruby, "fib.resume == 2", fib);
rb_assert!(ruby, "fib.resume == 3", fib);
rb_assert!(ruby, "fib.resume == 5", fib);
rb_assert!(ruby, "fib.resume == 8", fib);
Ok(())
}
Sourcepub fn fiber_new_from_fn<F, R>(
&self,
storage: Storage,
func: F,
) -> Result<Fiber, Error>
Available on ruby_gte_3_1
only.
pub fn fiber_new_from_fn<F, R>( &self, storage: Storage, func: F, ) -> Result<Fiber, Error>
ruby_gte_3_1
only.Create a Ruby Fiber.
See also fiber_new
, which is more efficient when
func
is a function or closure that does not capture any variables.
§Examples
use magnus::{rb_assert, Error, Ruby, Value};
fn example(ruby: &Ruby) -> Result<(), Error> {
let mut a = 0_u64;
let mut b = 1_u64;
let fib = ruby.fiber_new_from_fn(Default::default(), move |ruby, _args, _block| {
while let Some(c) = a.checked_add(b) {
let _: Value = ruby.fiber_yield((c,))?;
a = b;
b = c;
}
Ok(())
})?;
rb_assert!(ruby, "fib.resume == 1", fib);
rb_assert!(ruby, "fib.resume == 2", fib);
rb_assert!(ruby, "fib.resume == 3", fib);
rb_assert!(ruby, "fib.resume == 5", fib);
rb_assert!(ruby, "fib.resume == 8", fib);
Ok(())
}
Sourcepub fn fiber_current(&self) -> Fiber
Available on ruby_gte_3_1
only.
pub fn fiber_current(&self) -> Fiber
ruby_gte_3_1
only.Return the currently executing Fiber.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let fiber = ruby.fiber_current();
rb_assert!(ruby, "fiber.is_a?(Fiber)", fiber);
Ok(())
}
Sourcepub fn fiber_yield<A, T>(&self, args: A) -> Result<T, Error>where
A: ArgList,
T: TryConvert,
Available on ruby_gte_3_1
only.
pub fn fiber_yield<A, T>(&self, args: A) -> Result<T, Error>where
A: ArgList,
T: TryConvert,
ruby_gte_3_1
only.Transfer execution back to where the current Fiber was resumed.
§Examples
use magnus::{rb_assert, value::Opaque, Error, Ruby, Value};
fn example(ruby: &Ruby) -> Result<(), Error> {
let ary = ruby.ary_new();
let send_array = Opaque::from(ary);
let fiber = ruby.fiber_new_from_fn(Default::default(), move |ruby, _args, _block| {
let ary = ruby.get_inner(send_array);
ary.push(1)?;
let _: Value = ruby.fiber_yield(())?;
ary.push(2)?;
let _: Value = ruby.fiber_yield(())?;
ary.push(3)?;
let _: Value = ruby.fiber_yield(())?;
Ok(())
})?;
ary.push("a")?;
let _: Value = fiber.resume(())?;
ary.push("b")?;
let _: Value = fiber.resume(())?;
ary.push("c")?;
let _: Value = fiber.resume(())?;
rb_assert!(ruby, r#"ary == ["a", 1, "b", 2, "c", 3]"#, ary);
Ok(())
}
Source§impl Ruby
impl Ruby
See also the Float
type.
Sourcepub fn float_from_f64(&self, n: f64) -> Float
pub fn float_from_f64(&self, n: f64) -> Float
Create a new Float
from an f64
.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let f = ruby.float_from_f64(1.7272337110188893e-77);
rb_assert!(ruby, "f == 1.7272337110188893e-77", f);
let f = ruby.float_from_f64(1.7272337110188890e-77);
rb_assert!(ruby, "f == 1.7272337110188890e-77", f);
Ok(())
}
Source§impl Ruby
§GC
Functions for working with Ruby’s Garbage Collector.
impl Ruby
§GC
Functions for working with Ruby’s Garbage Collector.
See also the gc
module.
Sourcepub fn gc_disable(&self) -> bool
pub fn gc_disable(&self) -> bool
Disable automatic GC runs.
This could result in other Ruby api functions unexpectedly raising
NoMemError
.
Returns true
if GC was already disabled, false
otherwise.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let was_disabled = ruby.gc_disable();
// GC is off
// return GC to previous state
if !was_disabled {
ruby.gc_enable();
}
Ok(())
}
Sourcepub fn gc_enable(&self) -> bool
pub fn gc_enable(&self) -> bool
Enable automatic GC run.
Garbage Collection is enabled by default, calling this function only
makes sense if disable
was previously called.
Returns true
if GC was previously disabled, false
otherwise.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let was_disabled = ruby.gc_enable();
// GC is on
// return GC to previous state
if was_disabled {
ruby.gc_disable();
}
Ok(())
}
Sourcepub fn gc_start(&self)
pub fn gc_start(&self)
Trigger a “full” GC run.
This will perform a full mark phase and a complete sweep phase, but may not run every single process associated with garbage collection.
Finalisers will be deferred to run later.
Currently (with versions of Ruby that support compaction) it will not trigger compaction.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
ruby.gc_start();
Ok(())
}
Sourcepub fn gc_adjust_memory_usage(&self, diff: isize)
pub fn gc_adjust_memory_usage(&self, diff: isize)
Inform Ruby of external memory usage.
The Ruby GC is run when Ruby thinks it’s running out of memory, but won’t take into account any memory allocated outside of Ruby api functions. This function can be used to give Ruby a more accurate idea of how much memory the process is using.
Pass negative numbers to indicate memory has been freed.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let buf = Vec::<u8>::with_capacity(1024 * 1024);
let mem_size = buf.capacity() * std::mem::size_of::<u8>();
ruby.gc_adjust_memory_usage(mem_size as isize);
// ...
drop(buf);
ruby.gc_adjust_memory_usage(-(mem_size as isize));
Ok(())
}
Sourcepub fn gc_count(&self) -> usize
pub fn gc_count(&self) -> usize
Returns the number of garbage collections that have been run since the start of the process.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let before = ruby.gc_count();
ruby.gc_start();
assert!(ruby.gc_count() > before);
Ok(())
}
Sourcepub fn gc_stat<T>(&self, key: T) -> Result<usize, Error>where
T: IntoSymbol,
pub fn gc_stat<T>(&self, key: T) -> Result<usize, Error>where
T: IntoSymbol,
Returns the GC profiling value for key
.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
assert!(ruby.gc_stat("heap_live_slots")? > 1);
Ok(())
}
Sourcepub fn gc_all_stats(&self) -> RHash
pub fn gc_all_stats(&self) -> RHash
Source§impl Ruby
impl Ruby
See also the Integer
type.
Sourcepub fn integer_from_i64(&self, n: i64) -> Integer
pub fn integer_from_i64(&self, n: i64) -> Integer
Create a new Integer
from an i64.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "i == 0", i = ruby.integer_from_i64(0));
rb_assert!(
ruby,
"i == 4611686018427387904",
i = ruby.integer_from_i64(4611686018427387904),
);
rb_assert!(
ruby,
"i == -4611686018427387905",
i = ruby.integer_from_i64(-4611686018427387905),
);
Ok(())
}
Sourcepub fn integer_from_u64(&self, n: u64) -> Integer
pub fn integer_from_u64(&self, n: u64) -> Integer
Create a new Integer
from a u64.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!("i == 0", i = ruby.integer_from_u64(0));
rb_assert!(
"i == 4611686018427387904",
i = ruby.integer_from_u64(4611686018427387904),
);
Ok(())
}
Sourcepub fn integer_from_i128(&self, n: i128) -> Integer
pub fn integer_from_i128(&self, n: i128) -> Integer
Create a new Integer
from an i128.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "i == 0", i = ruby.integer_from_i128(0));
rb_assert!(
ruby,
"i == 170141183460469231731687303715884105727",
i = ruby.integer_from_i128(170141183460469231731687303715884105727),
);
rb_assert!(
ruby,
"i == -170141183460469231731687303715884105728",
i = ruby.integer_from_i128(-170141183460469231731687303715884105728),
);
Ok(())
}
Sourcepub fn integer_from_u128(&self, n: u128) -> Integer
pub fn integer_from_u128(&self, n: u128) -> Integer
Create a new Integer
from a u128.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!("i == 0", i = ruby.integer_from_u128(0));
rb_assert!(
"i == 340282366920938463463374607431768211455",
i = ruby.integer_from_u128(340282366920938463463374607431768211455),
);
Ok(())
}
Source§impl Ruby
impl Ruby
See also the IntoValue
trait.
Sourcepub fn into_value<T>(&self, val: T) -> Valuewhere
T: IntoValue,
pub fn into_value<T>(&self, val: T) -> Valuewhere
T: IntoValue,
Convert val
into Value
.
Source§impl Ruby
§IO helper functions
See also IoEncoding
type and FMode
type.
impl Ruby
§IO helper functions
See also IoEncoding
type and FMode
type.
Sourcepub fn io_extract_modeenc(
&self,
mode: &mut Value,
permission: &mut Value,
option: &RHash,
) -> Result<(OpenFlags, FMode, IoEncoding), Error>
Available on crate feature io
only.
pub fn io_extract_modeenc( &self, mode: &mut Value, permission: &mut Value, option: &RHash, ) -> Result<(OpenFlags, FMode, IoEncoding), Error>
io
only.Extract open flags and IO encoding metadata from a Ruby method call.
This wraps Ruby’s rb_io_extract_modeenc
function, which parses mode
, perm
, and options
into a combination of open flags, mode flags, and encoding metadata.
Can raise:
TypeError
if passed unexpected objects (e.g.,Time
)ArgError
if conflicting options are provided
Source§impl Ruby
§RModule
Functions that can be used to create Ruby modules.
impl Ruby
§RModule
Functions that can be used to create Ruby modules.
See also the RModule
type.
Sourcepub fn module_new(&self) -> RModule
pub fn module_new(&self) -> RModule
Create a new anonymous module.
§Examples
use magnus::{prelude::*, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let module = ruby.module_new();
assert!(module.is_kind_of(ruby.class_module()));
Ok(())
}
Source§impl Ruby
§Core Modules
Functions to access Ruby’s built-in modules.
impl Ruby
§Core Modules
Functions to access Ruby’s built-in modules.
See also Ruby::define_module
and the module
module.
Sourcepub fn module_comparable(&self) -> RModule
pub fn module_comparable(&self) -> RModule
Return Ruby’s Comparable
module.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "md == Comparable", md = ruby.module_comparable());
Ok(())
}
Sourcepub fn module_enumerable(&self) -> RModule
pub fn module_enumerable(&self) -> RModule
Return Ruby’s Enumerable
module.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "md == Enumerable", md = ruby.module_enumerable());
Ok(())
}
Sourcepub fn module_errno(&self) -> RModule
pub fn module_errno(&self) -> RModule
Return Ruby’s Errno
module.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "md == Errno", md = ruby.module_errno());
Ok(())
}
Sourcepub fn module_file_test(&self) -> RModule
pub fn module_file_test(&self) -> RModule
Return Ruby’s FileTest
module.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "md == FileTest", md = ruby.module_file_test());
Ok(())
}
Sourcepub fn module_gc(&self) -> RModule
pub fn module_gc(&self) -> RModule
Return Ruby’s GC
module.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "md == GC", md = ruby.module_gc());
Ok(())
}
Sourcepub fn module_kernel(&self) -> RModule
pub fn module_kernel(&self) -> RModule
Return Ruby’s Kernel
module.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "md == Kernel", md = ruby.module_kernel());
Ok(())
}
Sourcepub fn module_math(&self) -> RModule
pub fn module_math(&self) -> RModule
Return Ruby’s Math
module.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "md == Math", md = ruby.module_math());
Ok(())
}
Sourcepub fn module_process(&self) -> RModule
pub fn module_process(&self) -> RModule
Return Ruby’s Process
module.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(ruby, "md == Process", md = ruby.module_process());
Ok(())
}
Sourcepub fn module_wait_readable(&self) -> RModule
pub fn module_wait_readable(&self) -> RModule
Return Ruby’s IO::WaitReadable
module.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"md == IO::WaitReadable",
md = ruby.module_wait_readable()
);
Ok(())
}
Sourcepub fn module_wait_writable(&self) -> RModule
pub fn module_wait_writable(&self) -> RModule
Return Ruby’s IO::WaitWritable
module.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
rb_assert!(
ruby,
"md == IO::WaitWritable",
md = ruby.module_wait_writable()
);
Ok(())
}
Source§impl Ruby
§Process
Functions for working with processes.
impl Ruby
§Process
Functions for working with processes.
Sourcepub fn waitpid(
&self,
pid: WaitTarget,
flags: Flags,
) -> Result<Option<(NonZeroU32, ExitStatus)>, Error>
pub fn waitpid( &self, pid: WaitTarget, flags: Flags, ) -> Result<Option<(NonZeroU32, ExitStatus)>, Error>
Wait for a process.
This function releases Ruby’s Global VM Lock (GVL), so while it will block the current thread, other Ruby threads can be scheduled.
Returns the Process ID (PID) of the process waited, and its exit status.
If the NOHANG
flag is passed this function will not block, instead it
will clean up an exited child process if there is one, or returns
None
if there is no exited child process.
If the UNTRACED
flag is passed, this function will also return
stopped processes (e.g. that can be resumed), not only exited processes.
For these stopped processes the exit status will be reported as
successful, although they have not yet exited.
§Examples
use std::process::Command;
use magnus::{process::WaitTarget, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let child = Command::new("ls").spawn().unwrap();
let (pid, status) = ruby
.waitpid(WaitTarget::ChildPid(child.id()), Default::default())?
.unwrap();
assert_eq!(child.id(), pid.get());
assert!(status.success());
Ok(())
}
Source§impl Ruby
§RArray
Functions that can be used to create Ruby Array
s.
impl Ruby
§RArray
Functions that can be used to create Ruby Array
s.
See also the RArray
type.
Sourcepub fn ary_new(&self) -> RArray
pub fn ary_new(&self) -> RArray
Create a new empty RArray
.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let ary = ruby.ary_new();
assert!(ary.is_empty());
Ok(())
}
Sourcepub fn ary_new_capa(&self, n: usize) -> RArray
pub fn ary_new_capa(&self, n: usize) -> RArray
Create a new empty RArray
with capacity for n
elements
pre-allocated.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let ary = ruby.ary_new_capa(16);
assert!(ary.is_empty());
Ok(())
}
Sourcepub fn ary_from_vec<T>(&self, vec: Vec<T>) -> RArraywhere
T: IntoValueFromNative,
pub fn ary_from_vec<T>(&self, vec: Vec<T>) -> RArraywhere
T: IntoValueFromNative,
Create a new RArray
from a Rust vector.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let ary = ruby.ary_from_vec(vec![1, 2, 3]);
rb_assert!(ruby, "ary == [1, 2, 3]", ary);
Ok(())
}
Sourcepub fn ary_new_from_values<T>(&self, slice: &[T]) -> RArraywhere
T: ReprValue,
pub fn ary_new_from_values<T>(&self, slice: &[T]) -> RArraywhere
T: ReprValue,
Create a new RArray
containing the elements in slice
.
§Examples
use magnus::{prelude::*, rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let ary = ruby.ary_new_from_values(&[
ruby.to_symbol("a").as_value(),
ruby.integer_from_i64(1).as_value(),
ruby.qnil().as_value(),
]);
rb_assert!(ruby, "ary == [:a, 1, nil]", ary);
Ok(())
}
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let ary = ruby.ary_new_from_values(&[
ruby.to_symbol("a"),
ruby.to_symbol("b"),
ruby.to_symbol("c"),
]);
rb_assert!(ruby, "ary == [:a, :b, :c]", ary);
Ok(())
}
Sourcepub fn ary_from_iter<I, T>(&self, iter: I) -> RArraywhere
I: IntoIterator<Item = T>,
T: IntoValue,
pub fn ary_from_iter<I, T>(&self, iter: I) -> RArraywhere
I: IntoIterator<Item = T>,
T: IntoValue,
Create a new RArray
from a Rust iterator.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let ary = ruby.ary_from_iter((1..4).map(|i| i * 10));
rb_assert!(ruby, "ary == [10, 20, 30]", ary);
Ok(())
}
Sourcepub fn ary_try_from_iter<I, T, E>(&self, iter: I) -> Result<RArray, E>
pub fn ary_try_from_iter<I, T, E>(&self, iter: I) -> Result<RArray, E>
Create a new RArray
from a fallible Rust iterator.
Returns Ok(RArray)
on sucess or Err(E)
with the first error
encountered.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let ary = ruby
.ary_try_from_iter("1,2,3,4".split(',').map(|s| s.parse::<i64>()))
.map_err(|e| Error::new(ruby.exception_runtime_error(), e.to_string()))?;
rb_assert!(ruby, "ary == [1, 2, 3, 4]", ary);
Ok(())
}
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let err = ruby
.ary_try_from_iter("1,2,foo,4".split(',').map(|s| s.parse::<i64>()))
.unwrap_err();
assert_eq!(err.to_string(), "invalid digit found in string");
Ok(())
}
Sourcepub fn typed_ary_new<T>(&self) -> TypedArray<T>
pub fn typed_ary_new<T>(&self) -> TypedArray<T>
Create a new Ruby Array that may only contain elements of type T
.
On creation this Array is hidden from Ruby, and must be consumed to pass it to Ruby (where it reverts to a regular untyped Array). It is then inaccessible to Rust.
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let ary = ruby.typed_ary_new::<f64>();
ary.push("1".parse().unwrap())?;
ary.push("2.3".parse().unwrap())?;
ary.push("4.5".parse().unwrap())?;
rb_assert!(ruby, "ary == [1.0, 2.3, 4.5]", ary);
// ary has moved and can no longer be used.
Ok(())
}
Source§impl Ruby
§RBignum
Functions that can be used to create instances of Ruby’s large interger
representation.
impl Ruby
§RBignum
Functions that can be used to create instances of Ruby’s large interger representation.
See also the RBignum
type.
Sourcepub fn bignum_from_i64(&self, n: i64) -> Result<RBignum, Fixnum>
pub fn bignum_from_i64(&self, n: i64) -> Result<RBignum, Fixnum>
Create a new RBignum
from an i64.
Returns Ok(RBignum)
if n
is large enough to require a bignum,
otherwise returns Err(Fixnum)
.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
assert!(ruby.bignum_from_i64(4611686018427387904).is_ok());
assert!(ruby.bignum_from_i64(-4611686018427387905).is_ok());
// too small
assert!(ruby.bignum_from_i64(0).is_err());
Ok(())
}
Sourcepub fn bignum_from_u64(&self, n: u64) -> Result<RBignum, Fixnum>
pub fn bignum_from_u64(&self, n: u64) -> Result<RBignum, Fixnum>
Create a new RBignum
from an u64.
Returns Ok(RBignum)
if n
is large enough to require a bignum,
otherwise returns Err(Fixnum)
.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
assert!(ruby.bignum_from_u64(4611686018427387904).is_ok());
// too small
assert!(ruby.bignum_from_u64(0).is_err());
Ok(())
}
Source§impl Ruby
§RFloat
Functions that can be used to create Ruby Float
s.
impl Ruby
§RFloat
Functions that can be used to create Ruby Float
s.
See also the RFloat
type.
Sourcepub fn r_float_from_f64(&self, n: f64) -> Result<RFloat, Flonum>
pub fn r_float_from_f64(&self, n: f64) -> Result<RFloat, Flonum>
Create a new RFloat
from an f64.
Returns Ok(RFloat)
if n
requires a high precision float, otherwise
returns Err(Flonum)
.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let f = ruby.r_float_from_f64(1.7272337110188890e-77).unwrap();
rb_assert!(ruby, "f == 1.7272337110188890e-77", f);
// can fit within a Flonum, so does not require an RFloat
assert!(ruby.r_float_from_f64(1.7272337110188893e-77).is_err());
Ok(())
}
Source§impl Ruby
§RHash
Functions that can be used to create Ruby Hash
es.
impl Ruby
§RHash
Functions that can be used to create Ruby Hash
es.
See also the RHash
type.
Sourcepub fn hash_new(&self) -> RHash
pub fn hash_new(&self) -> RHash
Create a new empty RHash
.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let hash = ruby.hash_new();
assert!(hash.is_empty());
Ok(())
}
Sourcepub fn hash_new_capa(&self, n: usize) -> RHash
Available on ruby_gte_3_2
only.
pub fn hash_new_capa(&self, n: usize) -> RHash
ruby_gte_3_2
only.Create a new empty RHash
with capacity for n
elements pre-allocated.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let ary = ruby.hash_new_capa(16);
assert!(ary.is_empty());
Ok(())
}
Sourcepub fn hash_from_iter<I, K, V>(&self, iter: I) -> RHash
pub fn hash_from_iter<I, K, V>(&self, iter: I) -> RHash
Create a new RHash
from a Rust iterator.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let hash = ruby.hash_from_iter(["a", "b", "c"].into_iter().zip(1..4));
rb_assert!(ruby, r#"hash == {"a" => 1, "b" => 2, "c" => 3}"#, hash);
Ok(())
}
Sourcepub fn hash_try_from_iter<I, K, V, E>(&self, iter: I) -> Result<RHash, E>
pub fn hash_try_from_iter<I, K, V, E>(&self, iter: I) -> Result<RHash, E>
Create a new RHash
from a fallible Rust iterator.
Returns Ok(RHash)
on sucess or Err(E)
with the first error
encountered.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let hash = ruby.hash_try_from_iter("a,1;b,2;c,3".split(';').map(|s| {
s.split_once(',')
.ok_or_else(|| Error::new(ruby.exception_runtime_error(), "bad format"))
}))?;
rb_assert!(
ruby,
r#"hash == {"a" => "1", "b" => "2", "c" => "3"}"#,
hash
);
Ok(())
}
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let err = ruby
.hash_try_from_iter("a,1;b 2;c,3".split(';').map(|s| {
s.split_once(',')
.ok_or_else(|| Error::new(ruby.exception_runtime_error(), "bad format"))
}))
.unwrap_err();
assert_eq!(err.to_string(), "RuntimeError: bad format");
Ok(())
}
Source§impl Ruby
§RRational
Functions that can be used to create Ruby Rational
s.
impl Ruby
§RRational
Functions that can be used to create Ruby Rational
s.
See also the RRational
type.
Sourcepub fn rational_new(&self, num: i64, den: NonZeroI64) -> RRational
pub fn rational_new(&self, num: i64, den: NonZeroI64) -> RRational
Create a new RRational
.
§Examples
use std::num::NonZeroI64;
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let rational = ruby.rational_new(2, NonZeroI64::new(4).unwrap());
assert_eq!(rational.to_string(), "1/2");
Ok(())
}
Source§impl Ruby
§RRegexp
Functions that can be used to create Ruby Regexp
s.
impl Ruby
§RRegexp
Functions that can be used to create Ruby Regexp
s.
See also the RRegexp
type.
Sourcepub fn reg_new(&self, pattern: &str, opts: Opts) -> Result<RRegexp, Error>
pub fn reg_new(&self, pattern: &str, opts: Opts) -> Result<RRegexp, Error>
Create a new Regexp
from the Rust string pattern
.
The encoding of the Ruby regexp will be UTF-8.
§Examples
use magnus::{r_regexp::Opts, rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let regexp = ruby.reg_new("foo", Opts::new().ignorecase())?;
rb_assert!(ruby, r#"regexp == /foo/i"#, regexp);
Ok(())
}
Source§impl Ruby
§RString
Functions that can be used to create Ruby String
s.
impl Ruby
§RString
Functions that can be used to create Ruby String
s.
See also the RString
type.
Sourcepub fn str_new(&self, s: &str) -> RString ⓘ
pub fn str_new(&self, s: &str) -> RString ⓘ
Create a new Ruby string from the Rust string s
.
The encoding of the Ruby string will be UTF-8.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let val = ruby.str_new("example");
rb_assert!(ruby, r#"val == "example""#, val);
Ok(())
}
Sourcepub fn str_buf_new(&self, n: usize) -> RString ⓘ
pub fn str_buf_new(&self, n: usize) -> RString ⓘ
Create a new Ruby string with capacity n
.
The encoding will be set to ASCII-8BIT (aka BINARY). See also
with_capacity
.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let buf = ruby.str_buf_new(4096);
buf.cat(&[13, 14, 10, 13, 11, 14, 14, 15]);
rb_assert!(ruby, r#"buf == "\r\x0E\n\r\v\x0E\x0E\x0F""#, buf);
Ok(())
}
Sourcepub fn str_with_capacity(&self, n: usize) -> RString ⓘ
pub fn str_with_capacity(&self, n: usize) -> RString ⓘ
Create a new Ruby string with capacity n
.
The encoding will be set to UTF-8. See also
buf_new
.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let s = ruby.str_with_capacity(9);
s.cat("foo");
s.cat("bar");
s.cat("baz");
rb_assert!(ruby, r#"s == "foobarbaz""#, s);
Ok(())
}
Sourcepub fn str_from_slice(&self, s: &[u8]) -> RString ⓘ
pub fn str_from_slice(&self, s: &[u8]) -> RString ⓘ
Create a new Ruby string from the Rust slice s
.
The encoding of the Ruby string will be set to ASCII-8BIT (aka BINARY).
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let buf = ruby.str_from_slice(&[13, 14, 10, 13, 11, 14, 14, 15]);
rb_assert!(ruby, r#"buf == "\r\x0E\n\r\v\x0E\x0E\x0F""#, buf);
Ok(())
}
Sourcepub fn enc_str_new<T, E>(&self, s: T, enc: E) -> RString ⓘ
pub fn enc_str_new<T, E>(&self, s: T, enc: E) -> RString ⓘ
Create a new Ruby string from the value s
with the encoding enc
.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let val = ruby.enc_str_new("example", ruby.usascii_encoding());
rb_assert!(ruby, r#"val == "example""#, val);
Ok(())
}
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let val = ruby.enc_str_new([255, 128, 128], ruby.ascii8bit_encoding());
rb_assert!(
ruby,
r#"val == "\xFF\x80\x80".force_encoding("BINARY")"#,
val
);
Ok(())
}
Sourcepub fn str_from_char(&self, c: char) -> RString ⓘ
pub fn str_from_char(&self, c: char) -> RString ⓘ
Create a new Ruby string from the Rust char c
.
The encoding of the Ruby string will be UTF-8.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let c = ruby.str_from_char('a');
rb_assert!(ruby, r#"c == "a""#, c);
Ok(())
}
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let c = ruby.str_from_char('🦀');
rb_assert!(ruby, r#"c == "🦀""#, c);
Ok(())
}
Sourcepub fn chr<T>(&self, code: u32, enc: T) -> Result<RString, Error>where
T: Into<RbEncoding>,
pub fn chr<T>(&self, code: u32, enc: T) -> Result<RString, Error>where
T: Into<RbEncoding>,
Create a new Ruby string containing the codepoint code
in the
encoding enc
.
The encoding of the Ruby string will be the passed encoding enc
.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let c = ruby.chr(97, ruby.usascii_encoding())?;
rb_assert!(ruby, r#"c == "a""#, c);
Ok(())
}
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let c = ruby.chr(129408, ruby.utf8_encoding())?;
rb_assert!(ruby, r#"c == "🦀""#, c);
Ok(())
}
Source§impl Ruby
§Struct
Functions that can be used to create Ruby Struct
classes.
impl Ruby
§Struct
Functions that can be used to create Ruby Struct
classes.
See also the struct
module.
Sourcepub fn define_struct<T>(
&self,
name: Option<&str>,
members: T,
) -> Result<RClass, Error>where
T: StructMembers,
pub fn define_struct<T>(
&self,
name: Option<&str>,
members: T,
) -> Result<RClass, Error>where
T: StructMembers,
Define a Ruby Struct class.
members
is a tuple of &str
, of between lengths 1 to 12 inclusive.
§Examples
When providing None
for the name
the struct class’s name will be
taken from the first constant it is assigned to:
use magnus::{prelude::*, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let struct_class = ruby.define_struct(None, ("foo", "bar"))?;
ruby.define_global_const("Example", struct_class)?;
assert_eq!(unsafe { struct_class.name().to_owned() }, "Example");
let instance = struct_class.new_instance((1, 2))?;
assert_eq!(instance.inspect(), "#<struct Example foo=1, bar=2>");
Ok(())
}
When providing Some("Name")
for the name
the struct will be defined
under Struct
:
use magnus::{prelude::*, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let struct_class = ruby.define_struct(Some("Example"), ("foo", "bar"))?;
assert_eq!(unsafe { struct_class.name().to_owned() }, "Struct::Example");
let instance = struct_class.new_instance((1, 2))?;
assert_eq!(instance.inspect(), "#<struct Struct::Example foo=1, bar=2>");
Ok(())
}
Sourcepub fn define_data<T>(
&self,
super_class: Option<RClass>,
members: T,
) -> Result<RClass, Error>where
T: StructMembers,
Available on ruby_gte_3_3
only.
pub fn define_data<T>(
&self,
super_class: Option<RClass>,
members: T,
) -> Result<RClass, Error>where
T: StructMembers,
ruby_gte_3_3
only.Define a Ruby Data class.
If provided, super_class
must be a subclass of Ruby’s Data
class
(or Data
itself).
members
is a tuple of &str
, of between lengths 1 to 12 inclusive.
use magnus::{kwargs, prelude::*, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let data_class = ruby.define_data(None, ("foo", "bar"))?;
ruby.define_global_const("Example", data_class)?;
assert_eq!(unsafe { data_class.name().to_owned() }, "Example");
let instance = data_class.new_instance((kwargs!("foo" => 1, "bar" => 2),))?;
assert_eq!(instance.inspect(), "#<data Example foo=1, bar=2>");
Ok(())
}
Source§impl Ruby
§RTypedData
Functions to wrap Rust data in a Ruby object.
impl Ruby
§RTypedData
Functions to wrap Rust data in a Ruby object.
See also typed_data::Obj
and the RTypedData
type.
Sourcepub fn wrap<T>(&self, data: T) -> RTypedDatawhere
T: TypedData,
pub fn wrap<T>(&self, data: T) -> RTypedDatawhere
T: TypedData,
Wrap the Rust type T
in a Ruby object.
§Examples
use magnus::{prelude::*, Error, Ruby};
#[magnus::wrap(class = "Point")]
struct Point {
x: isize,
y: isize,
}
fn example(ruby: &Ruby) -> Result<(), Error> {
let point_class = ruby.define_class("Point", ruby.class_object())?;
let value = ruby.wrap(Point { x: 4, y: 2 });
assert!(value.is_kind_of(point_class));
Ok(())
}
Sourcepub fn wrap_as<T>(&self, data: T, class: RClass) -> RTypedDatawhere
T: TypedData,
pub fn wrap_as<T>(&self, data: T, class: RClass) -> RTypedDatawhere
T: TypedData,
Wrap the Rust type T
in a Ruby object that is an instance of the
given class
.
See also TypedData::class_for
.
§Panics
Panics if class
is not a subclass of <T as TypedData>::class()
.
§Examples
use magnus::{prelude::*, Error, Ruby};
#[magnus::wrap(class = "Point")]
struct Point {
x: isize,
y: isize,
}
fn example(ruby: &Ruby) -> Result<(), Error> {
let point_class = ruby.define_class("Point", ruby.class_object())?;
let point_sub_class = ruby.define_class("SubPoint", point_class)?;
let value = ruby.wrap_as(Point { x: 4, y: 2 }, point_sub_class);
assert!(value.is_kind_of(point_sub_class));
assert!(value.is_kind_of(point_class));
Ok(())
}
Allowing a wrapped type to be subclassed from Ruby:
(note, in this example Point
does not have and does not call
the initialize
method, subclasses would need to override the class
new
method rather than initialize
)
use magnus::{function, method, prelude::*, Error, RClass, RTypedData, Ruby, Value};
#[magnus::wrap(class = "Point")]
struct Point {
x: isize,
y: isize,
}
impl Point {
fn new(ruby: &Ruby, class: RClass, x: isize, y: isize) -> RTypedData {
ruby.wrap_as(Self { x, y }, class)
}
}
fn example(ruby: &Ruby) -> Result<(), Error> {
let point_class = ruby.define_class("Point", ruby.class_object())?;
point_class.define_singleton_method("new", method!(Point::new, 2))?;
point_class
.define_singleton_method("inherited", function!(RClass::undef_default_alloc_func, 1))?;
let value: Value = ruby.eval(
r#"
class SubPoint < Point
end
SubPoint.new(4, 2)
"#,
)?;
assert!(value.is_kind_of(ruby.class_object().const_get::<_, RClass>("SubPoint")?));
assert!(value.is_kind_of(point_class));
Ok(())
}
Source§impl Ruby
§Range
Functions that can be used to create Ruby Range
s.
impl Ruby
§Range
Functions that can be used to create Ruby Range
s.
See also the Range
type.
Sourcepub fn range_new<T, U>(
&self,
beg: T,
end: U,
excl: bool,
) -> Result<Range, Error>
pub fn range_new<T, U>( &self, beg: T, end: U, excl: bool, ) -> Result<Range, Error>
Create a new Range
.
Returns Err
if beg
and end
are not comparable.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let range = ruby.range_new(2, 7, false)?;
rb_assert!(ruby, "range == (2..7)", range);
Ok(())
}
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let range = ruby.range_new(2, 7, true)?;
rb_assert!(ruby, "range == (2...7)", range);
Ok(())
}
Source§impl Ruby
§Argument Parsing
Functions for handling argument parsing.
impl Ruby
§Argument Parsing
Functions for handling argument parsing.
See also the scan_args
module.
Sourcepub fn check_arity<T>(&self, len: usize, bounds: T) -> Result<(), Error>where
T: RangeBounds<usize>,
pub fn check_arity<T>(&self, len: usize, bounds: T) -> Result<(), Error>where
T: RangeBounds<usize>,
Returns Err
containing a Ruby ArgumentError
if len
is not within
bounds
.
§Examples
use magnus::{function, Error, RString, Ruby, Value};
fn test(ruby: &Ruby, args: &[Value]) -> Result<RString, Error> {
ruby.check_arity(args.len(), 2..5)?;
ruby.ary_new_from_values(args).join(", ")
}
fn example(ruby: &Ruby) -> Result<(), Error> {
ruby.define_global_function("test", function!(test, -1));
assert_eq!(
ruby.eval::<String>("test(1)").unwrap_err().to_string(),
"wrong number of arguments (given 1, expected 2..4)"
);
assert_eq!(
ruby.eval::<String>("test(1, 2, 3, 4, 5)")
.unwrap_err()
.to_string(),
"wrong number of arguments (given 5, expected 2..4)"
);
Ok(())
}
Source§impl Ruby
§Symbol
Functions that can be used to create Ruby Symbol
s.
impl Ruby
§Symbol
Functions that can be used to create Ruby Symbol
s.
See also the Symbol
type.
Source§impl Ruby
§Thread
Functions to create and work with Ruby Thread
s.
impl Ruby
§Thread
Functions to create and work with Ruby Thread
s.
See also the Thread
type.
Sourcepub fn thread_create<R>(&self, func: fn(&Ruby) -> R) -> Threadwhere
R: BlockReturn,
pub fn thread_create<R>(&self, func: fn(&Ruby) -> R) -> Threadwhere
R: BlockReturn,
Create a Ruby thread.
As func
is a function pointer, only functions and closures that do
not capture any variables are permitted. For more flexibility (at the
cost of allocating) see
thread_create_from_fn
.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let t = ruby.thread_create(|_ruby| 1 + 2);
rb_assert!("t.value == 3", t);
Ok(())
}
Sourcepub fn thread_create_from_fn<F, R>(&self, func: F) -> Thread
pub fn thread_create_from_fn<F, R>(&self, func: F) -> Thread
Create a Ruby thread.
See also thread_create
, which is more
efficient when func
is a function or closure that does not
capture any variables.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let i = 1;
let t = ruby.thread_create_from_fn(move |_ruby| i + 2);
rb_assert!("t.value == 3", t);
Ok(())
}
Sourcepub fn thread_current(&self) -> Thread
pub fn thread_current(&self) -> Thread
Return the currently executing thread.
§Examples
use magnus::{prelude::*, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let t = ruby.thread_current();
t.is_kind_of(ruby.class_thread());
Ok(())
}
Sourcepub fn thread_main(&self) -> Thread
pub fn thread_main(&self) -> Thread
Return the ‘main’ thread.
§Examples
use magnus::{prelude::*, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let t = ruby.thread_main();
t.is_kind_of(ruby.class_thread());
Ok(())
}
Sourcepub fn thread_schedule(&self)
pub fn thread_schedule(&self)
Attempt to schedule another thread.
This function blocks until the current thread is re-scheduled.
Sourcepub fn thread_wait_fd<T>(&self, fd: &T) -> Result<(), Error>where
T: AsRawFd,
pub fn thread_wait_fd<T>(&self, fd: &T) -> Result<(), Error>where
T: AsRawFd,
Blocks until the given file descriptor is readable.
§Examples
use std::{
io::{Read, Write},
net::Shutdown,
os::unix::net::UnixStream,
};
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let (mut a, mut b) = UnixStream::pair().unwrap();
a.write_all(b"hello, world!").unwrap();
a.shutdown(Shutdown::Both).unwrap();
b.set_nonblocking(true).unwrap();
ruby.thread_wait_fd(&b)?;
let mut s = String::new();
b.read_to_string(&mut s).unwrap();
assert_eq!(s, "hello, world!");
Ok(())
}
Sourcepub fn thread_fd_writable<T>(&self, fd: &T) -> Result<(), Error>where
T: AsRawFd,
pub fn thread_fd_writable<T>(&self, fd: &T) -> Result<(), Error>where
T: AsRawFd,
Blocks until the given file descriptor is writable.
§Examples
use std::{
io::{Read, Write},
net::Shutdown,
os::unix::net::UnixStream,
};
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let (mut a, mut b) = UnixStream::pair().unwrap();
a.set_nonblocking(true).unwrap();
ruby.thread_fd_writable(&a)?;
a.write_all(b"hello, world!").unwrap();
a.shutdown(Shutdown::Both).unwrap();
let mut s = String::new();
b.read_to_string(&mut s).unwrap();
assert_eq!(s, "hello, world!");
Ok(())
}
Sourcepub fn thread_fd_close<T>(&self, fd: &T) -> Result<(), Error>where
T: AsRawFd,
👎Deprecated: No-op as of Ruby 3.5
pub fn thread_fd_close<T>(&self, fd: &T) -> Result<(), Error>where
T: AsRawFd,
Schedules any Ruby threads waiting on fd
, notifying them that fd
has been closed.
Blocks until all threads waiting on fd
have woken up.
Sourcepub fn thread_alone(&self) -> bool
pub fn thread_alone(&self) -> bool
Checks if the current thread is the only thread currently alive.
§Examples
use std::time::Duration;
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
assert!(ruby.thread_alone());
ruby.thread_create_from_fn(|ruby| ruby.thread_sleep(Duration::from_secs(1)));
assert!(!ruby.thread_alone());
Ok(())
}
Sourcepub fn thread_sleep(&self, duration: Duration) -> Result<(), Error>
pub fn thread_sleep(&self, duration: Duration) -> Result<(), Error>
Blocks for the given period of time.
Returns an error if sleep is interrupted by a signal.
§Examples
use std::time::{Duration, Instant};
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let now = Instant::now();
ruby.thread_sleep(Duration::from_millis(100))?;
let elapsed = now.elapsed();
assert!(elapsed.as_millis() > 90);
assert!(elapsed.as_secs() < 1);
Ok(())
}
Sourcepub fn thread_sleep_forever(&self) -> Result<(), Error>
pub fn thread_sleep_forever(&self) -> Result<(), Error>
Blocks indefinitely.
Returns an error if sleep is interrupted by a signal.
Sourcepub fn thread_sleep_deadly(&self) -> Result<(), Error>
pub fn thread_sleep_deadly(&self) -> Result<(), Error>
Blocks indefinitely.
The thread calling this function is considered “dead” when Ruby’s
deadlock checker is triggered.
See also thread_sleep_forever
.
Returns an error if sleep is interrupted by a signal.
Sourcepub fn thread_stop(&self) -> Result<(), Error>
pub fn thread_stop(&self) -> Result<(), Error>
Stop the current thread.
The thread can later be woken up, see Thread::wakeup
.
Returns an error if stopping the current thread would deadlock.
Sourcepub fn thread_check_ints(&self) -> Result<(), Error>
pub fn thread_check_ints(&self) -> Result<(), Error>
Check for, and run, pending interrupts.
While Ruby is running a native extension function (such as one written
in Rust with Magnus) it can’t process interrupts (e.g. signals or
Thread#raise
called from another thread). Periodically calling this
function in any long running function will check for and run any
queued interrupts. This will allow your long running function to be
interrupted with say ctrl-c or Timeout::timeout
.
If any interrupt raises an error it will be returned as Err
.
Calling this function may execute code on another thread.
Source§impl Ruby
§Time
Functions to create and work with Ruby Time
objects.
impl Ruby
§Time
Functions to create and work with Ruby Time
objects.
See also the Time
type.
Sourcepub fn time_new(&self, seconds: i64, microseconds: i64) -> Result<Time, Error>
pub fn time_new(&self, seconds: i64, microseconds: i64) -> Result<Time, Error>
Create a new Time
in the local timezone.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let t = ruby.time_new(1654013280, 0)?;
rb_assert!(ruby, r#"t == Time.new(2022, 5, 31, 9, 8, 0, "-07:00")"#, t);
Ok(())
}
Sourcepub fn time_nano_new(
&self,
seconds: i64,
nanoseconds: i64,
) -> Result<Time, Error>
pub fn time_nano_new( &self, seconds: i64, nanoseconds: i64, ) -> Result<Time, Error>
Create a new Time
with nanosecond resolution in the local timezone.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let t = ruby.time_nano_new(1654013280, 0)?;
rb_assert!(ruby, r#"t == Time.new(2022, 5, 31, 9, 8, 0, "-07:00")"#, t);
Ok(())
}
Sourcepub fn time_timespec_new(
&self,
ts: Timespec,
offset: Offset,
) -> Result<Time, Error>
pub fn time_timespec_new( &self, ts: Timespec, offset: Offset, ) -> Result<Time, Error>
Create a new Time
with nanosecond resolution with the given offset.
§Examples
use magnus::{
error::IntoError,
rb_assert,
time::{Offset, Timespec},
Error, Ruby,
};
fn example(ruby: &Ruby) -> Result<(), Error> {
let ts = Timespec {
tv_sec: 1654013280,
tv_nsec: 0,
};
let offset = Offset::from_hours(-7).map_err(|e| e.into_error(ruby))?;
let t = ruby.time_timespec_new(ts, offset)?;
rb_assert!(ruby, r#"t == Time.new(2022, 5, 31, 9, 8, 0, "-07:00")"#, t);
Ok(())
}
Source§impl Ruby
§typed_data::Obj
Functions to wrap Rust data in a Ruby object.
impl Ruby
§typed_data::Obj
Functions to wrap Rust data in a Ruby object.
See also RTypedData
and the typed_data::Obj
type.
Sourcepub fn obj_wrap<T>(&self, data: T) -> Obj<T>where
T: TypedData,
pub fn obj_wrap<T>(&self, data: T) -> Obj<T>where
T: TypedData,
Wrap the Rust type T
in a Ruby object.
§Examples
use magnus::{prelude::*, Error, Ruby};
#[magnus::wrap(class = "Point")]
struct Point {
x: isize,
y: isize,
}
fn example(ruby: &Ruby) -> Result<(), Error> {
let point_class = ruby.define_class("Point", ruby.class_object())?;
let value = ruby.obj_wrap(Point { x: 4, y: 2 });
assert!(value.is_kind_of(point_class));
Ok(())
}
Sourcepub fn obj_wrap_as<T>(&self, data: T, class: RClass) -> Obj<T>where
T: TypedData,
pub fn obj_wrap_as<T>(&self, data: T, class: RClass) -> Obj<T>where
T: TypedData,
Wrap the Rust type T
in a Ruby object that is an instance of the
given class
.
See also TypedData::class_for
.
§Panics
Panics if class
is not a subclass of <T as TypedData>::class()
.
§Examples
use magnus::{prelude::*, Error, Ruby};
#[magnus::wrap(class = "Point")]
struct Point {
x: isize,
y: isize,
}
fn example(ruby: &Ruby) -> Result<(), Error> {
let point_class = ruby.define_class("Point", ruby.class_object())?;
let point_sub_class = ruby.define_class("SubPoint", point_class)?;
let value = ruby.obj_wrap_as(Point { x: 4, y: 2 }, point_sub_class);
assert!(value.is_kind_of(point_sub_class));
assert!(value.is_kind_of(point_class));
Ok(())
}
Allowing a wrapped type to be subclassed from Ruby:
(note, in this example Point
does not have and does not call the
initialize
method, subclasses would need to override the class new
method rather than initialize
)
use magnus::{function, method, prelude::*, typed_data, Error, RClass, Ruby, Value};
#[magnus::wrap(class = "Point")]
struct Point {
x: isize,
y: isize,
}
impl Point {
fn new(ruby: &Ruby, class: RClass, x: isize, y: isize) -> typed_data::Obj<Self> {
ruby.obj_wrap_as(Self { x, y }, class)
}
}
fn example(ruby: &Ruby) -> Result<(), Error> {
let point_class = ruby.define_class("Point", ruby.class_object())?;
point_class.define_singleton_method("new", method!(Point::new, 2))?;
point_class
.define_singleton_method("inherited", function!(RClass::undef_default_alloc_func, 1))?;
let value: Value = ruby.eval(
r#"
class SubPoint < Point
end
SubPoint.new(4, 2)
"#,
)?;
assert!(value.is_kind_of(ruby.class_object().const_get::<_, RClass>("SubPoint")?));
assert!(value.is_kind_of(point_class));
Ok(())
}
Source§impl Ruby
§Flonum
Functions that can be used to create instances of Ruby’s lower precision
floating point representation.
impl Ruby
§Flonum
Functions that can be used to create instances of Ruby’s lower precision floating point representation.
See also the Flonum
type.
Sourcepub fn flonum_from_f64(&self, n: f64) -> Result<Flonum, RFloat>
pub fn flonum_from_f64(&self, n: f64) -> Result<Flonum, RFloat>
Create a new Flonum
from a f64.
Returns Ok(Flonum)
if n
can be represented as a Flonum
, otherwise
returns Err(RFloat)
.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let f = ruby.flonum_from_f64(1.7272337110188893e-77).unwrap();
rb_assert!(ruby, "f == 1.7272337110188893e-77", f);
// representable as a Float, but Flonum does not have enough precision
assert!(ruby.flonum_from_f64(1.7272337110188890e-77).is_err());
Ok(())
}
Source§impl Ruby
§Extracting values from Opaque
/Lazy
Magnus has a number of container types where it is only safe to access the
inner Ruby value when you can provide a Ruby
handle. The functions here
provide a unified api to access those container types.
impl Ruby
§Extracting values from Opaque
/Lazy
Magnus has a number of container types where it is only safe to access the
inner Ruby value when you can provide a Ruby
handle. The functions here
provide a unified api to access those container types.
Sourcepub fn get_inner<T>(&self, wrapper: impl InnerValue<Value = T>) -> Twhere
T: ReprValue,
pub fn get_inner<T>(&self, wrapper: impl InnerValue<Value = T>) -> Twhere
T: ReprValue,
Get the inner value from wrapper
.
self
acts as a token proving this is called from a Ruby thread and
thus it is safe to return the inner value. See Opaque
and Lazy
.
§Examples
use magnus::{rb_assert, value::Opaque, Ruby};
let ruby = Ruby::get().unwrap();
let opaque_str = Opaque::from(ruby.str_new("example"));
// send to another Ruby thread
let ruby = Ruby::get().unwrap(); // errors on non-Ruby thread
let str = ruby.get_inner(opaque_str);
rb_assert!(ruby, r#"str == "example""#, str);
use magnus::{rb_assert, value::Lazy, RString, Ruby};
static STATIC_STR: Lazy<RString> = Lazy::new(|ruby| ruby.str_new("example"));
let ruby = Ruby::get().unwrap(); // errors if Ruby not initialised
let str = ruby.get_inner(&STATIC_STR);
rb_assert!(ruby, r#"str == "example""#, str);
Source§impl Ruby
§Fixnum
Functions that can be used to create instances of Ruby’s small/fast integer
representation.
impl Ruby
§Fixnum
Functions that can be used to create instances of Ruby’s small/fast integer representation.
See also the Fixnum
type.
Sourcepub fn fixnum_from_i64(&self, n: i64) -> Result<Fixnum, RBignum>
pub fn fixnum_from_i64(&self, n: i64) -> Result<Fixnum, RBignum>
Create a new Fixnum
from an i64.
Returns Ok(Fixnum)
if n
is in range for Fixnum
, otherwise returns
Err(RBignum)
.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
assert!(ruby.fixnum_from_i64(0).is_ok());
// too big
assert!(ruby.fixnum_from_i64(4611686018427387904).is_err());
assert!(ruby.fixnum_from_i64(-4611686018427387905).is_err());
Ok(())
}
Sourcepub fn fixnum_from_u64(&self, n: u64) -> Result<Fixnum, RBignum>
pub fn fixnum_from_u64(&self, n: u64) -> Result<Fixnum, RBignum>
Create a new Fixnum
from a u64.
Returns Ok(Fixnum)
if n
is in range for Fixnum
, otherwise returns
Err(RBignum)
.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
assert!(ruby.fixnum_from_u64(0).is_ok());
// too big
assert!(ruby.fixnum_from_u64(4611686018427387904).is_err());
Ok(())
}
Source§impl Ruby
§StaticSymbol
Functions to create Ruby Symbol
s that will never be garbage collected.
impl Ruby
§StaticSymbol
Functions to create Ruby Symbol
s that will never be garbage collected.
See also the StaticSymbol
type.
Sourcepub fn sym_new<T>(&self, name: T) -> StaticSymbolwhere
T: IntoId,
pub fn sym_new<T>(&self, name: T) -> StaticSymbolwhere
T: IntoId,
Create a new StaticSymbol.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let sym = ruby.sym_new("example");
rb_assert!(ruby, ":example == sym", sym);
Ok(())
}
Sourcepub fn check_symbol(&self, name: &str) -> Option<StaticSymbol>
pub fn check_symbol(&self, name: &str) -> Option<StaticSymbol>
Return the StaticSymbol
for name
, if one exists.
§Examples
use magnus::{Error, Ruby, StaticSymbol};
fn example(ruby: &Ruby) -> Result<(), Error> {
assert!(ruby.check_symbol("example").is_none());
let _: StaticSymbol = ruby.eval(":example")?;
assert!(ruby.check_symbol("example").is_some());
Ok(())
}
Source§impl Ruby
§Id
Functions to create Ruby’s low-level Symbol
representation.
impl Ruby
§Id
Functions to create Ruby’s low-level Symbol
representation.
See also the Id
type.
Source§impl Ruby
§Globals
Functions for defining global variables, constants, etc, as well as
accessing current Ruby execution status such as calling the current super
method.
impl Ruby
§Globals
Functions for defining global variables, constants, etc, as well as
accessing current Ruby execution status such as calling the current super
method.
See also functions in the root module.
Sourcepub fn define_class(
&self,
name: &str,
superclass: RClass,
) -> Result<RClass, Error>
pub fn define_class( &self, name: &str, superclass: RClass, ) -> Result<RClass, Error>
Define a class in the root scope.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
ruby.define_class("Example", ruby.class_object())?;
rb_assert!(ruby, "Example.is_a?(Class)");
Ok(())
}
Sourcepub fn define_module(&self, name: &str) -> Result<RModule, Error>
pub fn define_module(&self, name: &str) -> Result<RModule, Error>
Define a module in the root scope.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
ruby.define_module("Example")?;
rb_assert!(ruby, "Example.is_a?(Module)");
rb_assert!(ruby, "!Example.is_a?(Class)");
Ok(())
}
Sourcepub fn define_error(
&self,
name: &str,
superclass: ExceptionClass,
) -> Result<ExceptionClass, Error>
pub fn define_error( &self, name: &str, superclass: ExceptionClass, ) -> Result<ExceptionClass, Error>
Define an exception class in the root scope.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
ruby.define_error("ExampleError", ruby.exception_standard_error())?;
rb_assert!(ruby, "ExampleError.is_a?(Class)");
rb_assert!(ruby, "ExampleError < Exception");
Ok(())
}
Sourcepub fn define_variable<T>(
&self,
name: &str,
initial: T,
) -> Result<*mut Value, Error>where
T: IntoValue,
pub fn define_variable<T>(
&self,
name: &str,
initial: T,
) -> Result<*mut Value, Error>where
T: IntoValue,
Define a global variable.
§Examples
use magnus::{prelude::*, rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let v = ruby.define_variable("example", 42)?;
rb_assert!(ruby, "$example == 42");
// safe as long as another thread isn't modifying v
unsafe {
*v = ruby.str_new("answer").as_value();
}
rb_assert!(ruby, r#"$example == "answer""#);
Ok(())
}
Sourcepub fn alias_variable<T, U>(&self, dst: T, src: U) -> Result<(), Error>
pub fn alias_variable<T, U>(&self, dst: T, src: U) -> Result<(), Error>
Alias the global variable src
as dst
.
Unlike define_variable
, the preceding $
of the global variable’s name is required, otherwise the alias will not
be accessible from Ruby.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
ruby.define_variable("example", 42)?;
ruby.alias_variable("$answer", "$example")?;
rb_assert!(ruby, "$answer == 42");
Ok(())
}
Sourcepub fn define_global_const<T>(&self, name: &str, value: T) -> Result<(), Error>where
T: IntoValue,
pub fn define_global_const<T>(&self, name: &str, value: T) -> Result<(), Error>where
T: IntoValue,
Define a global constant.
§Examples
use magnus::{rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
ruby.define_global_const("EXAMPLE", 42)?;
rb_assert!(ruby, "EXAMPLE == 42");
Ok(())
}
Sourcepub fn define_global_function<M>(&self, name: &str, func: M)where
M: Method,
pub fn define_global_function<M>(&self, name: &str, func: M)where
M: Method,
Define a method in the root scope.
§Examples
use magnus::{function, rb_assert, Error, Ruby};
fn greet(subject: String) -> String {
format!("Hello, {}!", subject)
}
fn example(ruby: &Ruby) -> Result<(), Error> {
ruby.define_global_function("greet", function!(greet, 1));
rb_assert!(ruby, r#"greet("world") == "Hello, world!""#);
Ok(())
}
Sourcepub fn backref_get(&self) -> Option<RMatch>
pub fn backref_get(&self) -> Option<RMatch>
Returns the result of the most recent regexp match.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let regexp = ruby.reg_new("b(.)r", Default::default())?;
let result = regexp.reg_match("foo bar baz")?;
assert_eq!(result, Some(4));
let match_data = ruby.backref_get().unwrap();
assert_eq!(match_data.matched().to_string()?, String::from("bar"));
assert_eq!(
match_data.nth_match(1).map(|v| v.to_string().unwrap()),
Some(String::from("a"))
);
Ok(())
}
Sourcepub fn current_receiver<T>(&self) -> Result<T, Error>where
T: TryConvert,
pub fn current_receiver<T>(&self) -> Result<T, Error>where
T: TryConvert,
Return the Ruby self
of the current method context.
Returns Err
if called outside a method context or the conversion
fails.
§Examples
use magnus::{method, prelude::*, rb_assert, Error, Ruby, Value};
fn test(ruby: &Ruby, rb_self: Value) -> Result<bool, Error> {
rb_self.equal(ruby.current_receiver::<Value>()?)
}
fn example(ruby: &Ruby) -> Result<(), Error> {
ruby.define_global_function("test", method!(test, 0));
rb_assert!(ruby, "test");
Ok(())
}
Sourcepub fn call_super<A, T>(&self, args: A) -> Result<T, Error>where
A: ArgList,
T: TryConvert,
pub fn call_super<A, T>(&self, args: A) -> Result<T, Error>where
A: ArgList,
T: TryConvert,
Call the super method of the current method context.
Returns Ok(T)
if the super method exists and returns without error,
and the return value converts to a T
, or returns Err
if there is no
super method, the super method raises or the conversion fails.
§Examples
use magnus::{function, prelude::*, rb_assert, Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
let a = ruby.eval(
r#"
class A
def test
"Hello from A"
end
end
A
"#,
)?;
let b = ruby.define_class("B", a)?;
fn test(ruby: &Ruby) -> Result<String, Error> {
let s: String = ruby.call_super(())?;
Ok(format!("{}, and hello from B", s))
}
b.define_method("test", function!(test, 0))?;
rb_assert!(ruby, r#"B.new.test == "Hello from A, and hello from B""#);
Ok(())
}
Sourcepub fn require<T>(&self, feature: T) -> Result<bool, Error>where
T: IntoRString,
pub fn require<T>(&self, feature: T) -> Result<bool, Error>where
T: IntoRString,
Finds and loads the given feature if not already loaded.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
assert!(ruby.require("net/http")?);
Ok(())
}
Sourcepub fn eval<T>(&self, s: &str) -> Result<T, Error>where
T: TryConvert,
pub fn eval<T>(&self, s: &str) -> Result<T, Error>where
T: TryConvert,
Evaluate a string of Ruby code, converting the result to a T
.
Ruby will use the ‘ASCII-8BIT’ (aka binary) encoding for any Ruby
string literals in the passed string of Ruby code. See the
eval
macro for an alternative that supports
utf-8.
Errors if s
contains a null byte, the conversion fails, or on an
uncaught Ruby exception.
§Examples
use magnus::{Error, Ruby};
fn example(ruby: &Ruby) -> Result<(), Error> {
assert_eq!(ruby.eval::<i64>("1 + 2")?, 3);
Ok(())
}