#[repr(C)]pub struct Class { /* private fields */ }
Expand description
Class
Also see def
, def_self
, define
and some more functions from Object
trait.
#[macro_use] extern crate rutie;
use std::error::Error;
use rutie::{Class, Fixnum, Object, Exception, VM};
methods!(
Fixnum,
rtself,
fn pow(exp: Fixnum) -> Fixnum {
// `exp` is not a valid `Fixnum`, raise an exception
if let Err(ref error) = exp {
VM::raise(error.class(), &error.message());
}
// We can safely unwrap here, because an exception was raised if `exp` is `Err`
let exp = exp.unwrap().to_i64() as u32;
Fixnum::new(rtself.to_i64().pow(exp))
}
);
fn main() {
Class::from_existing("Fixnum").define(|klass| {
klass.def("pow", pow);
});
}
Ruby:
class Fixnum
def pow(exp)
raise TypeError unless exp.is_a?(Fixnum)
self ** exp
end
end
Implementations
sourceimpl Class
impl Class
sourcepub fn new(name: &str, superclass: Option<&Self>) -> Self
pub fn new(name: &str, superclass: Option<&Self>) -> Self
Creates a new Class
.
superclass
can receive the following values:
None
to inherit fromObject
class (standard Ruby behavior when superclass is not given explicitly);Some(&Class)
to inherit from the given class
Examples
use rutie::{Class, VM};
let basic_record_class = Class::new("BasicRecord", None);
assert_eq!(basic_record_class, Class::from_existing("BasicRecord"));
assert_eq!(basic_record_class.superclass(), Some(Class::from_existing("Object")));
let record_class = Class::new("Record", Some(&basic_record_class));
assert_eq!(record_class, Class::from_existing("Record"));
assert_eq!(record_class.superclass(), Some(Class::from_existing("BasicRecord")));
Ruby:
class BasicRecord
end
class Record < BasicRecord
end
BasicRecord.superclass == Object
Record.superclass == BasicRecord
sourcepub fn from_existing(name: &str) -> Self
pub fn from_existing(name: &str) -> Self
Retrieves an existing Class
object.
Examples
use rutie::{Class, VM};
let class = Class::new("Record", None);
assert_eq!(class, Class::from_existing("Record"));
Ruby:
class Record
end
Record
Object.const_get('Record')
sourcepub fn new_instance(&self, arguments: &[AnyObject]) -> AnyObject
pub fn new_instance(&self, arguments: &[AnyObject]) -> AnyObject
Creates a new instance of Class
Arguments must be passed as a vector of AnyObject
(see example).
Examples
use rutie::{Class, Fixnum, Object};
// Without arguments
Class::from_existing("Hello").new_instance(&[]);
// With arguments passing arguments to constructor
let arguments = [
Fixnum::new(1).to_any_object(),
Fixnum::new(2).to_any_object()
];
Class::from_existing("Worker").new_instance(&arguments);
Ruby:
Hello.new
Worker.new(1, 2)
sourcepub fn allocate(&self) -> Class
pub fn allocate(&self) -> Class
Creates a new instance of Class
Examples
use rutie::{Class, Object};
Class::from_existing("String").allocate();
Ruby:
String.allocate
sourcepub fn superclass(&self) -> Option<Class>
pub fn superclass(&self) -> Option<Class>
Returns a superclass of the current class
Examples
use rutie::{Class, Object, VM};
assert_eq!(
Class::from_existing("Array").superclass(),
Some(Class::from_existing("Object"))
);
assert_eq!(Class::from_existing("BasicObject").superclass(), None);
sourcepub fn ancestors(&self) -> Vec<Class>
pub fn ancestors(&self) -> Vec<Class>
Returns a Vector of ancestors of current class
Examples
Getting all the ancestors
use rutie::{Class, VM};
let true_class_ancestors = Class::from_existing("TrueClass").ancestors();
let expected_ancestors = vec![
Class::from_existing("TrueClass"),
Class::from_existing("Object"),
Class::from_existing("Kernel"),
Class::from_existing("BasicObject")
];
assert_eq!(true_class_ancestors, expected_ancestors);
Searching for an ancestor
use rutie::{Class, VM};
let basic_record_class = Class::new("BasicRecord", None);
let record_class = Class::new("Record", Some(&basic_record_class));
let ancestors = record_class.ancestors();
assert!(ancestors.iter().any(|class| *class == basic_record_class));
sourcepub fn get_nested_class(&self, name: &str) -> Self
pub fn get_nested_class(&self, name: &str) -> Self
Retrieves a Class
nested to current Class
.
Examples
use rutie::{Class, Object, VM};
Class::new("Outer", None).define(|klass| {
klass.define_nested_class("Inner", None);
});
Class::from_existing("Outer").get_nested_class("Inner");
Ruby:
class Outer
class Inner
end
end
Outer::Inner
Outer.const_get('Inner')
sourcepub fn get_nested_module(&self, name: &str) -> Module
pub fn get_nested_module(&self, name: &str) -> Module
Retrieves a Module
nested to current Class
.
Examples
use rutie::{Class, Module, Object, VM};
Class::new("Outer", None).define(|klass| {
klass.define_nested_module("Inner");
});
Class::from_existing("Outer").get_nested_module("Inner");
Ruby:
class Outer
module Inner
end
end
Outer::Inner
Outer.const_get('Inner')
sourcepub fn define_nested_class(
&mut self,
name: &str,
superclass: Option<&Class>
) -> Self
pub fn define_nested_class(
&mut self,
name: &str,
superclass: Option<&Class>
) -> Self
Creates a new Class
nested into current class.
superclass
can receive the following values:
None
to inherit fromObject
class (standard Ruby behavior when superclass is not given explicitly);Some(&class)
to inherit from the given class
Examples
use rutie::{Class, Object, VM};
Class::new("Outer", None).define(|klass| {
klass.define_nested_class("Inner", None);
});
Class::from_existing("Outer").get_nested_class("Inner");
Ruby:
class Outer
class Inner
end
end
Outer::Inner
Outer.const_get('Inner')
sourcepub fn define_nested_module(&mut self, name: &str) -> Module
pub fn define_nested_module(&mut self, name: &str) -> Module
Creates a new Module
nested into current Class
.
Examples
use rutie::{Class, Module, Object, VM};
Class::new("Outer", None).define(|klass| {
klass.define_nested_module("Inner");
});
Module::from_existing("Outer").get_nested_module("Inner");
Ruby:
class Outer
module Inner
end
end
Outer::Inner
Outer.const_get('Inner')
sourcepub fn const_get(&self, name: &str) -> AnyObject
pub fn const_get(&self, name: &str) -> AnyObject
Retrieves a constant from class.
Examples
use rutie::{Class, Object, RString, VM};
Class::new("Greeter", None).define(|klass| {
klass.const_set("GREETING", &RString::new_utf8("Hello, World!"));
});
let greeting = Class::from_existing("Greeter")
.const_get("GREETING")
.try_convert_to::<RString>()
.unwrap();
assert_eq!(greeting.to_str(), "Hello, World!");
Ruby:
class Greeter
GREETING = 'Hello, World!'
end
Greeter = Class.new
Greeter.const_set('GREETING', 'Hello, World!')
Greeter::GREETING == 'Hello, World!'
Greeter.const_get('GREETING') == 'Hello, World'
sourcepub fn const_set<T: Object>(&mut self, name: &str, value: &T)
pub fn const_set<T: Object>(&mut self, name: &str, value: &T)
Defines a constant for class.
Examples
use rutie::{Class, Object, RString, VM};
Class::new("Greeter", None).define(|klass| {
klass.const_set("GREETING", &RString::new_utf8("Hello, World!"));
});
let greeting = Class::from_existing("Greeter")
.const_get("GREETING")
.try_convert_to::<RString>()
.unwrap();
assert_eq!(greeting.to_str(), "Hello, World!");
Ruby:
class Greeter
GREETING = 'Hello, World!'
end
Greeter = Class.new
Greeter.const_set('GREETING', 'Hello, World!')
Greeter::GREETING == 'Hello, World!'
Greeter.const_get('GREETING') == 'Hello, World'
sourcepub fn include(&self, md: &str)
pub fn include(&self, md: &str)
Includes module into current class
Examples
use rutie::{Class, Module, VM};
let a_module = Module::new("A");
Class::new("B", None).include("A");
let b_class_ancestors = Class::from_existing("B").ancestors();
let expected_ancestors = vec![Module::from_existing("A")];
assert!(expected_ancestors.iter().any(|anc| *anc == a_module));
sourcepub fn prepend(&self, md: &str)
pub fn prepend(&self, md: &str)
Prepends module into current class
Examples
use rutie::{Class, Module, VM};
let a_module = Module::new("A");
Class::new("B", None).prepend("A");
let b_class_ancestors = Class::from_existing("B").ancestors();
let expected_ancestors = vec![Module::from_existing("A")];
assert!(expected_ancestors.iter().any(|anc| *anc == a_module));
sourcepub fn attr_reader(&mut self, name: &str)
pub fn attr_reader(&mut self, name: &str)
Defines an attr_reader
for class
Examples
use rutie::{Class, Object, VM};
Class::new("Test", None).define(|klass| {
klass.attr_reader("reader");
});
Ruby:
class Test
attr_reader :reader
end
sourcepub fn attr_writer(&mut self, name: &str)
pub fn attr_writer(&mut self, name: &str)
Defines an attr_writer
for class
Examples
use rutie::{Class, Object, VM};
Class::new("Test", None).define(|klass| {
klass.attr_writer("writer");
});
Ruby:
class Test
attr_writer :writer
end
sourcepub fn attr_accessor(&mut self, name: &str)
pub fn attr_accessor(&mut self, name: &str)
Defines an attr_accessor
for class
Examples
use rutie::{Class, Object, VM};
Class::new("Test", None).define(|klass| {
klass.attr_accessor("accessor");
});
Ruby:
class Test
attr_accessor :accessor
end
sourcepub fn wrap_data<T, O: Object>(
&self,
data: T,
wrapper: &dyn DataTypeWrapper<T>
) -> O
pub fn wrap_data<T, O: Object>(
&self,
data: T,
wrapper: &dyn DataTypeWrapper<T>
) -> O
Wraps Rust structure into a new Ruby object of the current class.
See the documentation for wrappable_struct!
macro for more information.
Examples
Wrap Server
structs to RubyServer
objects
#[macro_use] extern crate rutie;
#[macro_use] extern crate lazy_static;
use rutie::{AnyObject, Class, Fixnum, Object, RString, VM};
// The structure which we want to wrap
pub struct Server {
host: String,
port: u16,
}
impl Server {
fn new(host: String, port: u16) -> Self {
Server {
host: host,
port: port,
}
}
fn host(&self) -> &str {
&self.host
}
fn port(&self) -> u16 {
self.port
}
}
wrappable_struct!(Server, ServerWrapper, SERVER_WRAPPER);
class!(RubyServer);
methods!(
RubyServer,
rtself,
fn ruby_server_new(host: RString, port: Fixnum) -> AnyObject {
let server = Server::new(host.unwrap().to_string(),
port.unwrap().to_i64() as u16);
Class::from_existing("RubyServer").wrap_data(server, &*SERVER_WRAPPER)
}
fn ruby_server_host() -> RString {
let host = rtself.get_data(&*SERVER_WRAPPER).host();
RString::new_utf8(host)
}
fn ruby_server_port() -> Fixnum {
let port = rtself.get_data(&*SERVER_WRAPPER).port();
Fixnum::new(port as i64)
}
);
fn main() {
let data_class = Class::from_existing("Object");
Class::new("RubyServer", Some(&data_class)).define(|klass| {
klass.def_self("new", ruby_server_new);
klass.def("host", ruby_server_host);
klass.def("port", ruby_server_port);
});
}
To use the RubyServer
class in Ruby:
server = RubyServer.new("127.0.0.1", 3000)
server.host == "127.0.0.1"
server.port == 3000
Trait Implementations
sourceimpl Object for Class
impl Object for Class
sourcefn singleton_class(&self) -> Class
fn singleton_class(&self) -> Class
Returns a singleton class of current object. Read more
sourcefn get_data<'a, T>(&'a self, wrapper: &'a dyn DataTypeWrapper<T>) -> &T
fn get_data<'a, T>(&'a self, wrapper: &'a dyn DataTypeWrapper<T>) -> &T
Gets an immutable reference to the Rust structure which is wrapped into a Ruby object. Read more
sourcefn get_data_mut<'a, T>(
&'a mut self,
wrapper: &'a dyn DataTypeWrapper<T>
) -> &mut T
fn get_data_mut<'a, T>(
&'a mut self,
wrapper: &'a dyn DataTypeWrapper<T>
) -> &mut T
Gets a mutable reference to the Rust structure which is wrapped into a Ruby object.
sourcefn define_method<I: Object, O: Object>(
&mut self,
name: &str,
callback: Callback<I, O>
)
fn define_method<I: Object, O: Object>(
&mut self,
name: &str,
callback: Callback<I, O>
)
Defines an instance method for the given class or object. Read more
sourcefn define_private_method<I: Object, O: Object>(
&mut self,
name: &str,
callback: Callback<I, O>
)
fn define_private_method<I: Object, O: Object>(
&mut self,
name: &str,
callback: Callback<I, O>
)
Defines a private instance method for the given class or object. Read more
sourcefn define_singleton_method<I: Object, O: Object>(
&mut self,
name: &str,
callback: Callback<I, O>
)
fn define_singleton_method<I: Object, O: Object>(
&mut self,
name: &str,
callback: Callback<I, O>
)
Defines a class method for given class or singleton method for object. Read more
sourcefn def<I: Object, O: Object>(&mut self, name: &str, callback: Callback<I, O>)
fn def<I: Object, O: Object>(&mut self, name: &str, callback: Callback<I, O>)
An alias for define_method
(similar to Ruby syntax def some_method
).
sourcefn def_private<I: Object, O: Object>(
&mut self,
name: &str,
callback: Callback<I, O>
)
fn def_private<I: Object, O: Object>(
&mut self,
name: &str,
callback: Callback<I, O>
)
An alias for define_private_method
(similar to Ruby syntax private def some_method
).
sourcefn def_self<I: Object, O: Object>(
&mut self,
name: &str,
callback: Callback<I, O>
)
fn def_self<I: Object, O: Object>(
&mut self,
name: &str,
callback: Callback<I, O>
)
An alias for define_singleton_method
(similar to Ruby def self.some_method
).
sourceunsafe fn send(&self, method: &str, arguments: &[AnyObject]) -> AnyObject
unsafe fn send(&self, method: &str, arguments: &[AnyObject]) -> AnyObject
Calls a given method on an object similarly to Ruby Object#send
method Read more
sourcefn respond_to(&self, method: &str) -> bool
fn respond_to(&self, method: &str) -> bool
Checks whether the object responds to given method Read more
sourcefn protect_send(
&self,
method: &str,
arguments: &[AnyObject]
) -> Result<AnyObject, AnyException>
fn protect_send(
&self,
method: &str,
arguments: &[AnyObject]
) -> Result<AnyObject, AnyException>
protect_send
returns Result<AnyObject, AnyObject> Read more
sourcefn protect_public_send(
&self,
method: &str,
arguments: &[AnyObject]
) -> Result<AnyObject, AnyException>
fn protect_public_send(
&self,
method: &str,
arguments: &[AnyObject]
) -> Result<AnyObject, AnyException>
protect_public_send
returns Result<AnyObject, AnyObject> Read more
sourcefn to_any_object(&self) -> AnyObject
fn to_any_object(&self) -> AnyObject
Converts struct to AnyObject
Read more
sourcefn instance_variable_get(&self, variable: &str) -> AnyObject
fn instance_variable_get(&self, variable: &str) -> AnyObject
Gets an instance variable of object Read more
sourcefn instance_variable_set<T: Object>(
&mut self,
variable: &str,
value: T
) -> AnyObject
fn instance_variable_set<T: Object>(
&mut self,
variable: &str,
value: T
) -> AnyObject
Sets an instance variable for object Read more
sourceunsafe fn to<T: Object>(&self) -> T
unsafe fn to<T: Object>(&self) -> T
Unsafely casts current object to the specified Ruby type Read more
sourcefn try_convert_to<T: VerifiedObject>(&self) -> Result<T, AnyException>
fn try_convert_to<T: VerifiedObject>(&self) -> Result<T, AnyException>
Safely casts current object to the specified Ruby type Read more
sourceimpl VerifiedObject for Class
impl VerifiedObject for Class
fn is_correct_type<T: Object>(object: &T) -> bool
fn error_message() -> &'static str
Auto Trait Implementations
impl RefUnwindSafe for Class
impl Send for Class
impl Sync for Class
impl Unpin for Class
impl UnwindSafe for Class
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more