Class: Module
Overview
*********************************************************************
A Module is a collection of methods and constants. The
methods in a module may be instance methods or module methods.
Instance methods appear as methods in a class when the module is
included, module methods do not. Conversely, module methods may be
called without creating an encapsulating object, while instance
methods may not. (See Module#module_function.)
In the descriptions that follow, the parameter <i>sym</i> refers
to a symbol, which is either a quoted string or a
Symbol (such as <code>:name</code>).
module Mod
include Math
CONST = 1
def meth
# ...
end
end
Mod.class #=> Module
Mod.constants #=> [:CONST, :PI, :E]
Mod.instance_methods #=> [:meth]
Direct Known Subclasses
Class Method Summary collapse
-
.constants(*args) ⇒ Object
In the first form, returns an array of the names of all constants accessible from the point of call.
-
.nesting ⇒ Array
Returns the list of
Modules
nested at the point of call. -
.used_modules ⇒ Array
Returns an array of all modules used in the current scope.
-
.used_refinements ⇒ Array
Returns an array of all modules used in the current scope.
Instance Method Summary collapse
-
#<(other) ⇒ true, ...
Returns true if mod is a subclass of other.
-
#<=(other) ⇒ true, ...
Returns true if mod is a subclass of other or is the same as other.
-
#<=>(other_module) ⇒ -1, ...
Comparison—Returns -1, 0, +1 or nil depending on whether
module
includesother_module
, they are the same, or ifmodule
is included byother_module
. -
#==(obj2) ⇒ Object
Equality — At the Object level, #== returns
true
only ifobj
andother
are the same object. -
#===(obj) ⇒ Boolean
Case Equality—Returns
true
if obj is an instance of mod or an instance of one of mod’s descendants. -
#>(other) ⇒ true, ...
Returns true if mod is an ancestor of other.
-
#>=(other) ⇒ true, ...
Returns true if mod is an ancestor of other, or the two modules are the same.
-
#alias_method(new_name, old_name) ⇒ Object
Makes new_name a new copy of the method old_name.
-
#ancestors ⇒ Array
Returns a list of modules included/prepended in mod (including mod itself).
-
#append_features(mod) ⇒ Object
private
When this module is included in another, Ruby calls #append_features in this module, passing it the receiving module in mod.
-
#attr(*args) ⇒ Object
The first form is equivalent to #attr_reader.
-
#attr_accessor(*args) ⇒ Object
Defines a named attribute for this module, where the name is symbol.
id2name
, creating an instance variable (@name
) and a corresponding access method to read it. -
#attr_reader(*args) ⇒ Object
Creates instance variables and corresponding methods that return the value of each instance variable.
-
#attr_writer(*args) ⇒ Object
Creates an accessor method to allow assignment to the attribute symbol
.id2name
. -
#autoload(const, filename) ⇒ nil
Registers filename to be loaded (using Kernel::require) the first time that const (which may be a String or a symbol) is accessed in the namespace of mod.
-
#autoload?(name, inherit = true) ⇒ String?
Returns filename to be loaded if name is registered as
autoload
in the namespace of mod or one of its ancestors. -
#class_eval(*args) ⇒ Object
Evaluates the string or block in the context of mod, except that when a block is given, constant/class variable lookup is not affected.
-
#class_exec(*args) ⇒ Object
Evaluates the given block in the context of the class/module.
-
#class_variable_defined?(iv) ⇒ Object
Returns
true
if the given class variable is defined in obj. -
#class_variable_get(iv) ⇒ Object
Returns the value of the given class variable (or throws a NameError exception).
-
#class_variable_set(iv, val) ⇒ Object
Sets the class variable named by symbol to the given object.
-
#class_variables(inherit = true) ⇒ Array
Returns an array of the names of class variables in mod.
-
#const_added ⇒ Object
private
call-seq: const_added(const_name).
-
#const_defined?(*args) ⇒ Object
Says whether mod or its ancestors have a constant with the given name:.
-
#const_get(*args) ⇒ Object
Checks for a constant with the given name in mod.
-
#const_missing(sym) ⇒ Object
Invoked when a reference is made to an undefined constant in mod.
-
#const_set(name, value) ⇒ Object
Sets the named constant to the given object, returning that object.
-
#const_source_location(*args) ⇒ Object
Returns the Ruby source filename and line number containing the definition of the constant specified.
-
#constants(inherit = true) ⇒ Array
Returns an array of the names of the constants accessible in mod.
-
#define_method(*args) ⇒ Object
Defines an instance method in the receiver.
-
#deprecate_constant(symbol, ...) ⇒ Object
Makes a list of existing constants deprecated.
-
#extend_object(obj) ⇒ Object
private
Extends the specified object by adding this module’s constants and methods (which are added as singleton methods).
-
#extended ⇒ Object
private
call-seq: extended(othermod).
-
#freeze ⇒ Object
Prevents further modifications to mod.
-
#include ⇒ self
Invokes Module.append_features on each parameter in reverse order.
-
#include? ⇒ Boolean
Returns
true
if module is included or prepended in mod or one of mod’s ancestors. -
#included ⇒ Object
private
call-seq: included(othermod).
-
#included_modules ⇒ Array
Returns the list of modules included or prepended in mod or one of mod’s ancestors.
-
#initialize ⇒ Object
constructor
Creates a new anonymous module.
-
#initialize_clone(*args) ⇒ Object
:nodoc:.
-
#initialize_copy(orig) ⇒ Object
:nodoc:.
-
#instance_method(symbol) ⇒ Object
Returns an
UnboundMethod
representing the given instance method in mod. -
#instance_methods(include_super = true) ⇒ Array
Returns an array containing the names of the public and protected instance methods in the receiver.
-
#method_added ⇒ Object
private
call-seq: method_added(method_name).
-
#method_defined?(*args) ⇒ Object
Returns
true
if the named method is defined by mod. -
#method_removed ⇒ Object
private
call-seq: method_removed(method_name).
-
#method_undefined ⇒ Object
private
call-seq: method_undefined(method_name).
-
#module_eval(*args) ⇒ Object
Evaluates the string or block in the context of mod, except that when a block is given, constant/class variable lookup is not affected.
-
#module_exec(*args) ⇒ Object
Evaluates the given block in the context of the class/module.
-
#module_function(*args) ⇒ Object
private
Creates module functions for the named methods.
-
#name ⇒ String
Returns the name of the module mod.
-
#prepend ⇒ self
Invokes Module.prepend_features on each parameter in reverse order.
-
#prepend_features(mod) ⇒ Object
private
When this module is prepended in another, Ruby calls #prepend_features in this module, passing it the receiving module in mod.
-
#prepended ⇒ Object
private
call-seq: prepended(othermod).
-
#private(*args) ⇒ Object
private
With no arguments, sets the default visibility for subsequently defined methods to private.
-
#private_class_method(*args) ⇒ Object
Makes existing class methods private.
-
#private_constant(symbol, ...) ⇒ Object
Makes a list of existing constants private.
-
#private_instance_methods(include_super = true) ⇒ Array
Returns a list of the private instance methods defined in mod.
-
#private_method_defined?(*args) ⇒ Object
Returns
true
if the named private method is defined by mod. -
#protected(*args) ⇒ Object
private
With no arguments, sets the default visibility for subsequently defined methods to protected.
-
#protected_instance_methods(include_super = true) ⇒ Array
Returns a list of the protected instance methods defined in mod.
-
#protected_method_defined?(*args) ⇒ Object
Returns
true
if the named protected method is defined mod. -
#public(*args) ⇒ Object
private
With no arguments, sets the default visibility for subsequently defined methods to public.
-
#public_class_method(*args) ⇒ Object
Makes a list of existing class methods public.
-
#public_constant(symbol, ...) ⇒ Object
Makes a list of existing constants public.
-
#public_instance_method(symbol) ⇒ Object
Similar to instance_method, searches public method only.
-
#public_instance_methods(include_super = true) ⇒ Array
Returns a list of the public instance methods defined in mod.
-
#public_method_defined?(*args) ⇒ Object
Returns
true
if the named public method is defined by mod. -
#refine(mod) { ... } ⇒ Object
private
Refine mod in the receiver.
-
#refinements ⇒ Array
Returns an array of modules defined within the receiver.
-
#remove_class_variable(sym) ⇒ Object
Removes the named class variable from the receiver, returning that variable’s value.
-
#remove_const(sym) ⇒ Object
private
Removes the definition of the given constant, returning that constant’s previous value.
-
#remove_method(*args) ⇒ Object
Removes the method identified by symbol from the current class.
-
#ruby2_keywords(method_name, ...) ⇒ nil
private
For the given method names, marks the method as passing keywords through a normal argument splat.
-
#set_temporary_name(name) ⇒ Object
Sets the temporary name of the module.
-
#singleton_class? ⇒ Boolean
Returns
true
if mod is a singleton class orfalse
if it is an ordinary class or module. -
#to_s ⇒ String
(also: #inspect)
Returns a string representing this module or class.
-
#undef_method(*args) ⇒ Object
Prevents the current class from responding to calls to the named method.
-
#undefined_instance_methods ⇒ Array
Returns a list of the undefined instance methods defined in mod.
-
#using ⇒ self
private
Import class refinements from module into the current class or module definition.
Constructor Details
#new ⇒ Object #new {|mod| ... } ⇒ Object
Creates a new anonymous module. If a block is given, it is passed the module object, and the block is evaluated in the context of this module like #module_eval.
fred = Module.new do
def meth1
"hello"
end
def meth2
"bye"
end
end
a = "my string"
a.extend(fred) #=> "my string"
a.meth1 #=> "hello"
a.meth2 #=> "bye"
Assign the module to a constant (name starting uppercase) if you want to treat it like a regular module.
1949 1950 1951 1952 1953 |
# File 'object.c', line 1949
static VALUE
rb_mod_initialize(VALUE module)
{
return rb_mod_initialize_exec(module);
}
|
Class Method Details
.constants ⇒ Array .constants(inherited) ⇒ Array
In the first form, returns an array of the names of all constants accessible from the point of call. This list includes the names of all modules and classes defined in the global scope.
Module.constants.first(4)
# => [:ARGF, :ARGV, :ArgumentError, :Array]
Module.constants.include?(:SEEK_SET) # => false
class IO
Module.constants.include?(:SEEK_SET) # => true
end
The second form calls the instance method constants
.
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 |
# File 'eval.c', line 392
static VALUE
rb_mod_s_constants(int argc, VALUE *argv, VALUE mod)
{
const rb_cref_t *cref = rb_vm_cref();
VALUE klass;
VALUE cbase = 0;
void *data = 0;
if (argc > 0 || mod != rb_cModule) {
return rb_mod_constants(argc, argv, mod);
}
while (cref) {
klass = CREF_CLASS(cref);
if (!CREF_PUSHED_BY_EVAL(cref) &&
!NIL_P(klass)) {
data = rb_mod_const_at(CREF_CLASS(cref), data);
if (!cbase) {
cbase = klass;
}
}
cref = CREF_NEXT(cref);
}
if (cbase) {
data = rb_mod_const_of(cbase, data);
}
return rb_const_list(data);
}
|
.nesting ⇒ Array
Returns the list of Modules
nested at the point of call.
module M1
module M2
$a = Module.nesting
end
end
$a #=> [M1::M2, M1]
$a[0].name #=> "M1::M2"
353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 |
# File 'eval.c', line 353
static VALUE
rb_mod_nesting(VALUE _)
{
VALUE ary = rb_ary_new();
const rb_cref_t *cref = rb_vm_cref();
while (cref && CREF_NEXT(cref)) {
VALUE klass = CREF_CLASS(cref);
if (!CREF_PUSHED_BY_EVAL(cref) &&
!NIL_P(klass)) {
rb_ary_push(ary, klass);
}
cref = CREF_NEXT(cref);
}
return ary;
}
|
.used_modules ⇒ Array
1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 |
# File 'eval.c', line 1580
static VALUE
rb_mod_s_used_modules(VALUE _)
{
const rb_cref_t *cref = rb_vm_cref();
VALUE ary = rb_ary_new();
while (cref) {
if (!NIL_P(CREF_REFINEMENTS(cref))) {
rb_hash_foreach(CREF_REFINEMENTS(cref), used_modules_i, ary);
}
cref = CREF_NEXT(cref);
}
return rb_funcall(ary, rb_intern("uniq"), 0);
}
|
.used_refinements ⇒ Array
1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 |
# File 'eval.c', line 1631
static VALUE
rb_mod_s_used_refinements(VALUE _)
{
const rb_cref_t *cref = rb_vm_cref();
VALUE ary = rb_ary_new();
while (cref) {
if (!NIL_P(CREF_REFINEMENTS(cref))) {
rb_hash_foreach(CREF_REFINEMENTS(cref), used_refinements_i, ary);
}
cref = CREF_NEXT(cref);
}
return ary;
}
|
Instance Method Details
#<(other) ⇒ true, ...
Returns true if mod is a subclass of other. Returns false
if mod is the same as other or mod is an ancestor of other. Returns nil
if there’s no relationship between the two. (Think of the relationship in terms of the class definition: “class A < B” implies “A < B”.)
1841 1842 1843 1844 1845 1846 |
# File 'object.c', line 1841
static VALUE
rb_mod_lt(VALUE mod, VALUE arg)
{
if (mod == arg) return Qfalse;
return rb_class_inherited_p(mod, arg);
}
|
#<=(other) ⇒ true, ...
Returns true if mod is a subclass of other or is the same as other. Returns nil
if there’s no relationship between the two. (Think of the relationship in terms of the class definition: “class A < B” implies “A < B”.)
1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 |
# File 'object.c', line 1787
VALUE
rb_class_inherited_p(VALUE mod, VALUE arg)
{
if (mod == arg) return Qtrue;
if (RB_TYPE_P(arg, T_CLASS) && RB_TYPE_P(mod, T_CLASS)) {
// comparison between classes
size_t mod_depth = RCLASS_SUPERCLASS_DEPTH(mod);
size_t arg_depth = RCLASS_SUPERCLASS_DEPTH(arg);
if (arg_depth < mod_depth) {
// check if mod < arg
return RCLASS_SUPERCLASSES(mod)[arg_depth] == arg ?
Qtrue :
Qnil;
}
else if (arg_depth > mod_depth) {
// check if mod > arg
return RCLASS_SUPERCLASSES(arg)[mod_depth] == mod ?
Qfalse :
Qnil;
}
else {
// Depths match, and we know they aren't equal: no relation
return Qnil;
}
}
else {
if (!CLASS_OR_MODULE_P(arg) && !RB_TYPE_P(arg, T_ICLASS)) {
rb_raise(rb_eTypeError, "compared with non class/module");
}
if (class_search_ancestor(mod, RCLASS_ORIGIN(arg))) {
return Qtrue;
}
/* not mod < arg; check if mod > arg */
if (class_search_ancestor(arg, mod)) {
return Qfalse;
}
return Qnil;
}
}
|
#<=>(other_module) ⇒ -1, ...
Comparison—Returns -1, 0, +1 or nil depending on whether module
includes other_module
, they are the same, or if module
is included by other_module
.
Returns nil
if module
has no relationship with other_module
, if other_module
is not a module, or if the two values are incomparable.
1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 |
# File 'object.c', line 1903
static VALUE
rb_mod_cmp(VALUE mod, VALUE arg)
{
VALUE cmp;
if (mod == arg) return INT2FIX(0);
if (!CLASS_OR_MODULE_P(arg)) {
return Qnil;
}
cmp = rb_class_inherited_p(mod, arg);
if (NIL_P(cmp)) return Qnil;
if (cmp) {
return INT2FIX(-1);
}
return INT2FIX(1);
}
|
#==(other) ⇒ Boolean #equal?(other) ⇒ Boolean #eql?(other) ⇒ Boolean
Equality — At the Object level, #== returns true
only if obj
and other
are the same object. Typically, this method is overridden in descendant classes to provide class-specific meaning.
Unlike #==, the #equal? method should never be overridden by subclasses as it is used to determine object identity (that is, a.equal?(b)
if and only if a
is the same object as b
):
obj = "a"
other = obj.dup
obj == other #=> true
obj.equal? other #=> false
obj.equal? obj #=> true
The #eql? method returns true
if obj
and other
refer to the same hash key. This is used by Hash to test members for equality. For any pair of objects where #eql? returns true
, the #hash value of both objects must be equal. So any subclass that overrides #eql? should also override #hash appropriately.
For objects of class Object, #eql? is synonymous with #==. Subclasses normally continue this tradition by aliasing #eql? to their overridden #== method, but there are exceptions. Numeric types, for example, perform type conversion across #==, but not across #eql?, so:
1 == 1.0 #=> true
1.eql? 1.0 #=> false
213 214 215 216 217 |
# File 'object.c', line 213
VALUE
rb_obj_equal(VALUE obj1, VALUE obj2)
{
return RBOOL(obj1 == obj2);
}
|
#===(obj) ⇒ Boolean
Case Equality—Returns true
if obj is an instance of mod or an instance of one of mod’s descendants. Of limited use for modules, but can be used in case
statements to classify objects by class.
1770 1771 1772 1773 1774 |
# File 'object.c', line 1770
static VALUE
rb_mod_eqq(VALUE mod, VALUE arg)
{
return rb_obj_is_kind_of(arg, mod);
}
|
#>(other) ⇒ true, ...
Returns true if mod is an ancestor of other. Returns false
if mod is the same as other or mod is a descendant of other. Returns nil
if there’s no relationship between the two. (Think of the relationship in terms of the class definition: “class A < B” implies “B > A”.)
1884 1885 1886 1887 1888 1889 |
# File 'object.c', line 1884
static VALUE
rb_mod_gt(VALUE mod, VALUE arg)
{
if (mod == arg) return Qfalse;
return rb_mod_ge(mod, arg);
}
|
#>=(other) ⇒ true, ...
Returns true if mod is an ancestor of other, or the two modules are the same. Returns nil
if there’s no relationship between the two. (Think of the relationship in terms of the class definition: “class A < B” implies “B > A”.)
1861 1862 1863 1864 1865 1866 1867 1868 1869 |
# File 'object.c', line 1861
static VALUE
rb_mod_ge(VALUE mod, VALUE arg)
{
if (!CLASS_OR_MODULE_P(arg)) {
rb_raise(rb_eTypeError, "compared with non class/module");
}
return rb_class_inherited_p(arg, mod);
}
|
#alias_method(new_name, old_name) ⇒ Object
Makes new_name a new copy of the method old_name. This can be used to retain access to methods that are overridden.
module Mod
alias_method :orig_exit, :exit #=> :orig_exit
def exit(code=0)
puts "Exiting with code #{code}"
orig_exit(code)
end
end
include Mod
exit(99)
produces:
Exiting with code 99
2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 |
# File 'vm_method.c', line 2354
static VALUE
rb_mod_alias_method(VALUE mod, VALUE newname, VALUE oldname)
{
ID oldid = rb_check_id(&oldname);
if (!oldid) {
rb_print_undef_str(mod, oldname);
}
VALUE id = rb_to_id(newname);
rb_alias(mod, id, oldid);
return ID2SYM(id);
}
|
#ancestors ⇒ Array
Returns a list of modules included/prepended in mod (including mod itself).
module Mod
include Math
include Comparable
prepend Enumerable
end
Mod.ancestors #=> [Enumerable, Mod, Comparable, Math]
Math.ancestors #=> [Math]
Enumerable.ancestors #=> [Enumerable]
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 |
# File 'class.c', line 1569
VALUE
rb_mod_ancestors(VALUE mod)
{
VALUE p, ary = rb_ary_new();
VALUE refined_class = Qnil;
if (BUILTIN_TYPE(mod) == T_MODULE && FL_TEST(mod, RMODULE_IS_REFINEMENT)) {
refined_class = rb_refinement_module_get_refined_class(mod);
}
for (p = mod; p; p = RCLASS_SUPER(p)) {
if (p == refined_class) break;
if (p != RCLASS_ORIGIN(p)) continue;
if (BUILTIN_TYPE(p) == T_ICLASS) {
rb_ary_push(ary, METACLASS_OF(p));
}
else {
rb_ary_push(ary, p);
}
}
return ary;
}
|
#append_features(mod) ⇒ Object (private)
When this module is included in another, Ruby calls #append_features in this module, passing it the receiving module in mod. Ruby’s default implementation is to add the constants, methods, and module variables of this module to mod if this module has not already been added to mod or one of its ancestors. See also Module#include.
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 |
# File 'eval.c', line 1120
static VALUE
rb_mod_append_features(VALUE module, VALUE include)
{
if (!CLASS_OR_MODULE_P(include)) {
Check_Type(include, T_CLASS);
}
rb_include_module(include, module);
return module;
}
|
#attr(name, ...) ⇒ Array #attr(name, true) ⇒ Array #attr(name, false) ⇒ Array
The first form is equivalent to #attr_reader. The second form is equivalent to attr_accessor(name)
but deprecated. The last form is equivalent to attr_reader(name)
but deprecated. Returns an array of defined method names as symbols.
2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 |
# File 'object.c', line 2307
VALUE
rb_mod_attr(int argc, VALUE *argv, VALUE klass)
{
if (argc == 2 && (argv[1] == Qtrue || argv[1] == Qfalse)) {
ID id = id_for_attr(klass, argv[0]);
VALUE names = rb_ary_new();
rb_category_warning(RB_WARN_CATEGORY_DEPRECATED, "optional boolean argument is obsoleted");
rb_attr(klass, id, 1, RTEST(argv[1]), TRUE);
rb_ary_push(names, ID2SYM(id));
if (argv[1] == Qtrue) rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
return names;
}
return rb_mod_attr_reader(argc, argv, klass);
}
|
#attr_accessor(symbol, ...) ⇒ Array #attr_accessor(string, ...) ⇒ Array
Defines a named attribute for this module, where the name is symbol.id2name
, creating an instance variable (@name
) and a corresponding access method to read it. Also creates a method called name=
to set the attribute. String arguments are converted to symbols. Returns an array of defined method names as symbols.
module Mod
attr_accessor(:one, :two) #=> [:one, :one=, :two, :two=]
end
Mod.instance_methods.sort #=> [:one, :one=, :two, :two=]
2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 |
# File 'object.c', line 2366
static VALUE
rb_mod_attr_accessor(int argc, VALUE *argv, VALUE klass)
{
int i;
VALUE names = rb_ary_new2(argc * 2);
for (i=0; i<argc; i++) {
ID id = id_for_attr(klass, argv[i]);
rb_attr(klass, id, TRUE, TRUE, TRUE);
rb_ary_push(names, ID2SYM(id));
rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
}
return names;
}
|
#attr_reader(symbol, ...) ⇒ Array #attr(symbol, ...) ⇒ Array #attr_reader(string, ...) ⇒ Array #attr(string, ...) ⇒ Array
Creates instance variables and corresponding methods that return the value of each instance variable. Equivalent to calling “attr
:name” on each name in turn. String arguments are converted to symbols. Returns an array of defined method names as symbols.
2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 |
# File 'object.c', line 2278
static VALUE
rb_mod_attr_reader(int argc, VALUE *argv, VALUE klass)
{
int i;
VALUE names = rb_ary_new2(argc);
for (i=0; i<argc; i++) {
ID id = id_for_attr(klass, argv[i]);
rb_attr(klass, id, TRUE, FALSE, TRUE);
rb_ary_push(names, ID2SYM(id));
}
return names;
}
|
#attr_writer(symbol, ...) ⇒ Array #attr_writer(string, ...) ⇒ Array
Creates an accessor method to allow assignment to the attribute symbol.id2name
. String arguments are converted to symbols. Returns an array of defined method names as symbols.
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 |
# File 'object.c', line 2334
static VALUE
rb_mod_attr_writer(int argc, VALUE *argv, VALUE klass)
{
int i;
VALUE names = rb_ary_new2(argc);
for (i=0; i<argc; i++) {
ID id = id_for_attr(klass, argv[i]);
rb_attr(klass, id, FALSE, TRUE, TRUE);
rb_ary_push(names, ID2SYM(rb_id_attrset(id)));
}
return names;
}
|
#autoload(const, filename) ⇒ nil
Registers filename to be loaded (using Kernel::require) the first time that const (which may be a String or a symbol) is accessed in the namespace of mod.
module A
end
A.autoload(:B, "b")
A::B.doit # autoloads "b"
If const in mod is defined as autoload, the file name to be loaded is replaced with filename. If const is defined but not as autoload, does nothing.
1453 1454 1455 1456 1457 1458 1459 1460 1461 |
# File 'load.c', line 1453
static VALUE
rb_mod_autoload(VALUE mod, VALUE sym, VALUE file)
{
ID id = rb_to_id(sym);
FilePathValue(file);
rb_autoload_str(mod, id, file);
return Qnil;
}
|
#autoload?(name, inherit = true) ⇒ String?
Returns filename to be loaded if name is registered as autoload
in the namespace of mod or one of its ancestors.
module A
end
A.autoload(:B, "b")
A.autoload?(:B) #=> "b"
If inherit
is false, the lookup only checks the autoloads in the receiver:
class A
autoload :CONST, "const.rb"
end
class B < A
end
B.autoload?(:CONST) #=> "const.rb", found in A (ancestor)
B.autoload?(:CONST, false) #=> nil, not found in B itself
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 |
# File 'load.c', line 1489
static VALUE
rb_mod_autoload_p(int argc, VALUE *argv, VALUE mod)
{
int recur = (rb_check_arity(argc, 1, 2) == 1) ? TRUE : RTEST(argv[1]);
VALUE sym = argv[0];
ID id = rb_check_id(&sym);
if (!id) {
return Qnil;
}
return rb_autoload_at_p(mod, id, recur);
}
|
#class_eval(string[, filename [, lineno]]) ⇒ Object #class_eval {|mod| ... } ⇒ Object #module_eval(string[, filename [, lineno]]) ⇒ Object #module_eval {|mod| ... } ⇒ Object
Evaluates the string or block in the context of mod, except that when a block is given, constant/class variable lookup is not affected. This can be used to add methods to a class. module_eval
returns the result of evaluating its argument. The optional filename and lineno parameters set the text for error messages.
class Thing
end
a = %q{def hello() "Hello there!" end}
Thing.module_eval(a)
puts Thing.new.hello()
Thing.module_eval("invalid code", "dummy", 123)
produces:
Hello there!
dummy:123:in `module_eval': undefined local variable
or method `code' for Thing:Class
2121 2122 2123 2124 2125 |
# File 'vm_eval.c', line 2121
static VALUE
rb_mod_module_eval_internal(int argc, const VALUE *argv, VALUE mod)
{
return specific_eval(argc, argv, mod, FALSE, RB_PASS_CALLED_KEYWORDS);
}
|
#module_exec(arg...) {|var...| ... } ⇒ Object #class_exec(arg...) {|var...| ... } ⇒ Object
Evaluates the given block in the context of the class/module. The method defined in the block will belong to the receiver. Any arguments passed to the method will be passed to the block. This can be used if the block needs to access instance variables.
class Thing
end
Thing.class_exec{
def hello() "Hello there!" end
}
puts Thing.new.hello()
produces:
Hello there!
2155 2156 2157 2158 2159 |
# File 'vm_eval.c', line 2155
static VALUE
rb_mod_module_exec_internal(int argc, const VALUE *argv, VALUE mod)
{
return yield_under(mod, FALSE, argc, argv, RB_PASS_CALLED_KEYWORDS);
}
|
#class_variable_defined?(symbol) ⇒ Boolean #class_variable_defined?(string) ⇒ Boolean
Returns true
if the given class variable is defined in obj. String arguments are converted to symbols.
class Fred
@@foo = 99
end
Fred.class_variable_defined?(:@@foo) #=> true
Fred.class_variable_defined?(:@@bar) #=> false
3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 |
# File 'object.c', line 3025
static VALUE
rb_mod_cvar_defined(VALUE obj, VALUE iv)
{
ID id = id_for_var(obj, iv, class);
if (!id) {
return Qfalse;
}
return rb_cvar_defined(obj, id);
}
|
#class_variable_get(symbol) ⇒ Object #class_variable_get(string) ⇒ Object
Returns the value of the given class variable (or throws a NameError exception). The @@
part of the variable name should be included for regular class variables. String arguments are converted to symbols.
class Fred
@@foo = 99
end
Fred.class_variable_get(:@@foo) #=> 99
2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 |
# File 'object.c', line 2968
static VALUE
rb_mod_cvar_get(VALUE obj, VALUE iv)
{
ID id = id_for_var(obj, iv, class);
if (!id) {
rb_name_err_raise("uninitialized class variable %1$s in %2$s",
obj, iv);
}
return rb_cvar_get(obj, id);
}
|
#class_variable_set(symbol, obj) ⇒ Object #class_variable_set(string, obj) ⇒ Object
Sets the class variable named by symbol to the given object. If the class variable name is passed as a string, that string is converted to a symbol.
class Fred
@@foo = 99
def foo
@@foo
end
end
Fred.class_variable_set(:@@foo, 101) #=> 101
Fred.new.foo #=> 101
3000 3001 3002 3003 3004 3005 3006 3007 |
# File 'object.c', line 3000
static VALUE
rb_mod_cvar_set(VALUE obj, VALUE iv, VALUE val)
{
ID id = id_for_var(obj, iv, class);
if (!id) id = rb_intern_str(iv);
rb_cvar_set(obj, id, val);
return val;
}
|
#class_variables(inherit = true) ⇒ Array
Returns an array of the names of class variables in mod. This includes the names of class variables in any included modules, unless the inherit parameter is set to false
.
class One
@@var1 = 1
end
class Two < One
@@var2 = 2
end
One.class_variables #=> [:@@var1]
Two.class_variables #=> [:@@var2, :@@var1]
Two.class_variables(false) #=> [:@@var2]
4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 |
# File 'variable.c', line 4197
VALUE
rb_mod_class_variables(int argc, const VALUE *argv, VALUE mod)
{
bool inherit = true;
st_table *tbl;
if (rb_check_arity(argc, 0, 1)) inherit = RTEST(argv[0]);
if (inherit) {
tbl = mod_cvar_of(mod, 0);
}
else {
tbl = mod_cvar_at(mod, 0);
}
return cvar_list(tbl);
}
|
#const_added ⇒ Object (private)
call-seq:
const_added(const_name)
Invoked as a callback whenever a constant is assigned on the receiver
module Chatty
def self.const_added(const_name)
super
puts "Added #{const_name.inspect}"
end
FOO = 1
end
produces:
Added :FOO
#const_defined?(sym, inherit = true) ⇒ Boolean #const_defined?(str, inherit = true) ⇒ Boolean
Says whether mod or its ancestors have a constant with the given name:
Float.const_defined?(:EPSILON) #=> true, found in Float itself
Float.const_defined?("String") #=> true, found in Object (ancestor)
BasicObject.const_defined?(:Hash) #=> false
If mod is a Module
, additionally Object
and its ancestors are checked:
Math.const_defined?(:String) #=> true, found in Object
In each of the checked classes or modules, if the constant is not present but there is an autoload for it, true
is returned directly without autoloading:
module Admin
autoload :User, 'admin/user'
end
Admin.const_defined?(:User) #=> true
If the constant is not found the callback const_missing
is not called and the method returns false
.
If inherit
is false, the lookup only checks the constants in the receiver:
IO.const_defined?(:SYNC) #=> true, found in File::Constants (ancestor)
IO.const_defined?(:SYNC, false) #=> false, not found in IO itself
In this case, the same logic for autoloading applies.
If the argument is not a valid constant name a NameError
is raised with the message “wrong constant name name”:
Hash.const_defined? 'foobar' #=> NameError: wrong constant name foobar
2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 |
# File 'object.c', line 2595
static VALUE
rb_mod_const_defined(int argc, VALUE *argv, VALUE mod)
{
VALUE name, recur;
rb_encoding *enc;
const char *pbeg, *p, *path, *pend;
ID id;
rb_check_arity(argc, 1, 2);
name = argv[0];
recur = (argc == 1) ? Qtrue : argv[1];
if (SYMBOL_P(name)) {
if (!rb_is_const_sym(name)) goto wrong_name;
id = rb_check_id(&name);
if (!id) return Qfalse;
return RTEST(recur) ? rb_const_defined(mod, id) : rb_const_defined_at(mod, id);
}
path = StringValuePtr(name);
enc = rb_enc_get(name);
if (!rb_enc_asciicompat(enc)) {
rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
}
pbeg = p = path;
pend = path + RSTRING_LEN(name);
if (p >= pend || !*p) {
goto wrong_name;
}
if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
mod = rb_cObject;
p += 2;
pbeg = p;
}
while (p < pend) {
VALUE part;
long len, beglen;
while (p < pend && *p != ':') p++;
if (pbeg == p) goto wrong_name;
id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
beglen = pbeg-path;
if (p < pend && p[0] == ':') {
if (p + 2 >= pend || p[1] != ':') goto wrong_name;
p += 2;
pbeg = p;
}
if (!id) {
part = rb_str_subseq(name, beglen, len);
OBJ_FREEZE(part);
if (!rb_is_const_name(part)) {
name = part;
goto wrong_name;
}
else {
return Qfalse;
}
}
if (!rb_is_const_id(id)) {
name = ID2SYM(id);
goto wrong_name;
}
#if 0
mod = rb_const_search(mod, id, beglen > 0 || !RTEST(recur), RTEST(recur), FALSE);
if (UNDEF_P(mod)) return Qfalse;
#else
if (!RTEST(recur)) {
if (!rb_const_defined_at(mod, id))
return Qfalse;
if (p == pend) return Qtrue;
mod = rb_const_get_at(mod, id);
}
else if (beglen == 0) {
if (!rb_const_defined(mod, id))
return Qfalse;
if (p == pend) return Qtrue;
mod = rb_const_get(mod, id);
}
else {
if (!rb_const_defined_from(mod, id))
return Qfalse;
if (p == pend) return Qtrue;
mod = rb_const_get_from(mod, id);
}
#endif
if (p < pend && !RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
QUOTE(name));
}
}
return Qtrue;
wrong_name:
rb_name_err_raise(wrong_constant_name, mod, name);
UNREACHABLE_RETURN(Qundef);
}
|
#const_get(sym, inherit = true) ⇒ Object #const_get(str, inherit = true) ⇒ Object
Checks for a constant with the given name in mod. If inherit
is set, the lookup will also search the ancestors (and Object
if mod is a Module
).
The value of the constant is returned if a definition is found, otherwise a NameError
is raised.
Math.const_get(:PI) #=> 3.14159265358979
This method will recursively look up constant names if a namespaced class name is provided. For example:
module Foo; class Bar; end end
Object.const_get 'Foo::Bar'
The inherit
flag is respected on each lookup. For example:
module Foo
class Bar
VAL = 10
end
class Baz < Bar; end
end
Object.const_get 'Foo::Baz::VAL' # => 10
Object.const_get 'Foo::Baz::VAL', false # => NameError
If the argument is not a valid constant name a NameError
will be raised with a warning “wrong constant name”.
Object.const_get ‘foobar’ #=> NameError: wrong constant name foobar
2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 |
# File 'object.c', line 2422
static VALUE
rb_mod_const_get(int argc, VALUE *argv, VALUE mod)
{
VALUE name, recur;
rb_encoding *enc;
const char *pbeg, *p, *path, *pend;
ID id;
rb_check_arity(argc, 1, 2);
name = argv[0];
recur = (argc == 1) ? Qtrue : argv[1];
if (SYMBOL_P(name)) {
if (!rb_is_const_sym(name)) goto wrong_name;
id = rb_check_id(&name);
if (!id) return rb_const_missing(mod, name);
return RTEST(recur) ? rb_const_get(mod, id) : rb_const_get_at(mod, id);
}
path = StringValuePtr(name);
enc = rb_enc_get(name);
if (!rb_enc_asciicompat(enc)) {
rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
}
pbeg = p = path;
pend = path + RSTRING_LEN(name);
if (p >= pend || !*p) {
goto wrong_name;
}
if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
mod = rb_cObject;
p += 2;
pbeg = p;
}
while (p < pend) {
VALUE part;
long len, beglen;
while (p < pend && *p != ':') p++;
if (pbeg == p) goto wrong_name;
id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
beglen = pbeg-path;
if (p < pend && p[0] == ':') {
if (p + 2 >= pend || p[1] != ':') goto wrong_name;
p += 2;
pbeg = p;
}
if (!RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
QUOTE(name));
}
if (!id) {
part = rb_str_subseq(name, beglen, len);
OBJ_FREEZE(part);
if (!rb_is_const_name(part)) {
name = part;
goto wrong_name;
}
else if (!rb_method_basic_definition_p(CLASS_OF(mod), id_const_missing)) {
part = rb_str_intern(part);
mod = rb_const_missing(mod, part);
continue;
}
else {
rb_mod_const_missing(mod, part);
}
}
if (!rb_is_const_id(id)) {
name = ID2SYM(id);
goto wrong_name;
}
#if 0
mod = rb_const_get_0(mod, id, beglen > 0 || !RTEST(recur), RTEST(recur), FALSE);
#else
if (!RTEST(recur)) {
mod = rb_const_get_at(mod, id);
}
else if (beglen == 0) {
mod = rb_const_get(mod, id);
}
else {
mod = rb_const_get_from(mod, id);
}
#endif
}
return mod;
wrong_name:
rb_name_err_raise(wrong_constant_name, mod, name);
UNREACHABLE_RETURN(Qundef);
}
|
#const_missing(sym) ⇒ Object
Invoked when a reference is made to an undefined constant in mod. It is passed a symbol for the undefined constant, and returns a value to be used for that constant. The following code is an example of the same:
def Foo.const_missing(name)
name # return the constant name as Symbol
end
Foo::UNDEFINED_CONST #=> :UNDEFINED_CONST: symbol returned
In the next example when a reference is made to an undefined constant, it attempts to load a file whose name is the lowercase version of the constant (thus class Fred
is assumed to be in file fred.rb
). If found, it returns the loaded class. It therefore implements an autoload feature similar to Kernel#autoload and Module#autoload.
def Object.const_missing(name)
@looked_for ||= {}
str_name = name.to_s
raise "Class not found: #{name}" if @looked_for[str_name]
@looked_for[str_name] = 1
file = str_name.downcase
require file
klass = const_get(name)
return klass if klass
raise "Class not found: #{name}"
end
2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 |
# File 'variable.c', line 2402
VALUE
rb_mod_const_missing(VALUE klass, VALUE name)
{
rb_execution_context_t *ec = GET_EC();
VALUE ref = ec->private_const_reference;
rb_vm_pop_cfunc_frame();
if (ref) {
ec->private_const_reference = 0;
rb_name_err_raise("private constant %2$s::%1$s referenced", ref, name);
}
uninitialized_constant(klass, name);
UNREACHABLE_RETURN(Qnil);
}
|
#const_set(sym, obj) ⇒ Object #const_set(str, obj) ⇒ Object
Sets the named constant to the given object, returning that object. Creates a new constant if no constant with the given name previously existed.
Math.const_set("HIGH_SCHOOL_PI", 22.0/7.0) #=> 3.14285714285714
Math::HIGH_SCHOOL_PI - Math::PI #=> 0.00126448926734968
If sym
or str
is not a valid constant name a NameError
will be raised with a warning “wrong constant name”.
Object.const_set(‘foobar’, 42) #=> NameError: wrong constant name foobar
2544 2545 2546 2547 2548 2549 2550 2551 2552 |
# File 'object.c', line 2544
static VALUE
rb_mod_const_set(VALUE mod, VALUE name, VALUE value)
{
ID id = id_for_var(mod, name, const);
if (!id) id = rb_intern_str(name);
rb_const_set(mod, id, value);
return value;
}
|
#const_source_location(sym, inherit = true) ⇒ Array, Integer #const_source_location(str, inherit = true) ⇒ Array, Integer
Returns the Ruby source filename and line number containing the definition of the constant specified. If the named constant is not found, nil
is returned. If the constant is found, but its source location can not be extracted (constant is defined in C code), empty array is returned.
inherit specifies whether to lookup in mod.ancestors
(true
by default).
# test.rb:
class A # line 1
C1 = 1
C2 = 2
end
module M # line 6
C3 = 3
end
class B < A # line 10
include M
C4 = 4
end
class A # continuation of A definition
C2 = 8 # constant redefinition; warned yet allowed
end
p B.const_source_location('C4') # => ["test.rb", 12]
p B.const_source_location('C3') # => ["test.rb", 7]
p B.const_source_location('C1') # => ["test.rb", 2]
p B.const_source_location('C3', false) # => nil -- don't lookup in ancestors
p A.const_source_location('C2') # => ["test.rb", 16] -- actual (last) definition place
p Object.const_source_location('B') # => ["test.rb", 10] -- top-level constant could be looked through Object
p Object.const_source_location('A') # => ["test.rb", 1] -- class reopening is NOT considered new definition
p B.const_source_location('A') # => ["test.rb", 1] -- because Object is in ancestors
p M.const_source_location('A') # => ["test.rb", 1] -- Object is not ancestor, but additionally checked for modules
p Object.const_source_location('A::C1') # => ["test.rb", 2] -- nesting is supported
p Object.const_source_location('String') # => [] -- constant is defined in C code
2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 |
# File 'object.c', line 2755
static VALUE
rb_mod_const_source_location(int argc, VALUE *argv, VALUE mod)
{
VALUE name, recur, loc = Qnil;
rb_encoding *enc;
const char *pbeg, *p, *path, *pend;
ID id;
rb_check_arity(argc, 1, 2);
name = argv[0];
recur = (argc == 1) ? Qtrue : argv[1];
if (SYMBOL_P(name)) {
if (!rb_is_const_sym(name)) goto wrong_name;
id = rb_check_id(&name);
if (!id) return Qnil;
return RTEST(recur) ? rb_const_source_location(mod, id) : rb_const_source_location_at(mod, id);
}
path = StringValuePtr(name);
enc = rb_enc_get(name);
if (!rb_enc_asciicompat(enc)) {
rb_raise(rb_eArgError, "invalid class path encoding (non ASCII)");
}
pbeg = p = path;
pend = path + RSTRING_LEN(name);
if (p >= pend || !*p) {
goto wrong_name;
}
if (p + 2 < pend && p[0] == ':' && p[1] == ':') {
mod = rb_cObject;
p += 2;
pbeg = p;
}
while (p < pend) {
VALUE part;
long len, beglen;
while (p < pend && *p != ':') p++;
if (pbeg == p) goto wrong_name;
id = rb_check_id_cstr(pbeg, len = p-pbeg, enc);
beglen = pbeg-path;
if (p < pend && p[0] == ':') {
if (p + 2 >= pend || p[1] != ':') goto wrong_name;
p += 2;
pbeg = p;
}
if (!id) {
part = rb_str_subseq(name, beglen, len);
OBJ_FREEZE(part);
if (!rb_is_const_name(part)) {
name = part;
goto wrong_name;
}
else {
return Qnil;
}
}
if (!rb_is_const_id(id)) {
name = ID2SYM(id);
goto wrong_name;
}
if (p < pend) {
if (RTEST(recur)) {
mod = rb_const_get(mod, id);
}
else {
mod = rb_const_get_at(mod, id);
}
if (!RB_TYPE_P(mod, T_MODULE) && !RB_TYPE_P(mod, T_CLASS)) {
rb_raise(rb_eTypeError, "%"PRIsVALUE" does not refer to class/module",
QUOTE(name));
}
}
else {
if (RTEST(recur)) {
loc = rb_const_source_location(mod, id);
}
else {
loc = rb_const_source_location_at(mod, id);
}
break;
}
recur = Qfalse;
}
return loc;
wrong_name:
rb_name_err_raise(wrong_constant_name, mod, name);
UNREACHABLE_RETURN(Qundef);
}
|
#constants(inherit = true) ⇒ Array
Returns an array of the names of the constants accessible in mod. This includes the names of constants in any included modules (example at start of section), unless the inherit parameter is set to false
.
The implementation makes no guarantees about the order in which the constants are yielded.
IO.constants.include?(:SYNC) #=> true
IO.constants(false).include?(:SYNC) #=> false
Also see Module#const_defined?.
3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 |
# File 'variable.c', line 3473
VALUE
rb_mod_constants(int argc, const VALUE *argv, VALUE mod)
{
bool inherit = true;
if (rb_check_arity(argc, 0, 1)) inherit = RTEST(argv[0]);
if (inherit) {
return rb_const_list(rb_mod_const_of(mod, 0));
}
else {
return rb_local_constants(mod);
}
}
|
#define_method(symbol, method) ⇒ Object #define_method(symbol) { ... } ⇒ Object
Defines an instance method in the receiver. The method parameter can be a Proc
, a Method
or an UnboundMethod
object. If a block is specified, it is used as the method body. If a block or the method parameter has parameters, they’re used as method parameters. This block is evaluated using #instance_eval.
class A
def fred
puts "In Fred"
end
def create_method(name, &block)
self.class.define_method(name, &block)
end
define_method(:wilma) { puts "Charge it!" }
define_method(:flint) {|name| puts "I'm #{name}!"}
end
class B < A
define_method(:barney, instance_method(:fred))
end
a = B.new
a.
a.wilma
a.flint('Dino')
a.create_method(:betty) { p self }
a.betty
produces:
In Fred
Charge it!
I'm Dino!
#<B:0x401b39e8>
2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 |
# File 'proc.c', line 2318
static VALUE
rb_mod_define_method(int argc, VALUE *argv, VALUE mod)
{
const rb_cref_t *cref = rb_vm_cref_in_context(mod, mod);
const rb_scope_visibility_t default_scope_visi = {METHOD_VISI_PUBLIC, FALSE};
const rb_scope_visibility_t *scope_visi = &default_scope_visi;
if (cref) {
scope_visi = CREF_SCOPE_VISI(cref);
}
return rb_mod_define_method_with_visibility(argc, argv, mod, scope_visi);
}
|
#deprecate_constant(symbol, ...) ⇒ Object
Makes a list of existing constants deprecated. Attempt to refer to them will produce a warning.
module HTTP
NotFound = Exception.new
NOT_FOUND = NotFound # previous version of the library used this name
deprecate_constant :NOT_FOUND
end
HTTP::NOT_FOUND
# warning: constant HTTP::NOT_FOUND is deprecated
3894 3895 3896 3897 3898 3899 |
# File 'variable.c', line 3894
VALUE
rb_mod_deprecate_constant(int argc, const VALUE *argv, VALUE obj)
{
set_const_visibility(obj, argc, argv, CONST_DEPRECATED, CONST_DEPRECATED);
return obj;
}
|
#extend_object(obj) ⇒ Object (private)
Extends the specified object by adding this module’s constants and methods (which are added as singleton methods). This is the callback method used by Object#extend.
module Picky
def Picky.extend_object(o)
if String === o
puts "Can't add Picky to a String"
else
puts "Picky added to #{o.class}"
super
end
end
end
(s = Array.new).extend Picky # Call Object.extend
(s = "quick brown fox").extend Picky
produces:
Picky added to Array
Can't add Picky to a String
1745 1746 1747 1748 1749 1750 |
# File 'eval.c', line 1745
static VALUE
rb_mod_extend_object(VALUE mod, VALUE obj)
{
rb_extend_object(obj, mod);
return obj;
}
|
#extended ⇒ Object (private)
call-seq:
extended(othermod)
The equivalent of included
, but for extended modules.
module A
def self.extended(mod)
puts "#{self} extended in #{mod}"
end
end
module Enumerable
extend A
end
# => prints "A extended in Enumerable"
#freeze ⇒ Object
Prevents further modifications to mod.
This method returns self.
1753 1754 1755 1756 1757 1758 |
# File 'object.c', line 1753
static VALUE
rb_mod_freeze(VALUE mod)
{
rb_class_name(mod);
return rb_obj_freeze(mod);
}
|
#include ⇒ self
Invokes Module.append_features on each parameter in reverse order.
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 |
# File 'eval.c', line 1138
static VALUE
rb_mod_include(int argc, VALUE *argv, VALUE module)
{
int i;
ID id_append_features, id_included;
CONST_ID(id_append_features, "append_features");
CONST_ID(id_included, "included");
if (BUILTIN_TYPE(module) == T_MODULE && FL_TEST(module, RMODULE_IS_REFINEMENT)) {
rb_raise(rb_eTypeError, "Refinement#include has been removed");
}
rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
for (i = 0; i < argc; i++) {
Check_Type(argv[i], T_MODULE);
if (FL_TEST(argv[i], RMODULE_IS_REFINEMENT)) {
rb_raise(rb_eTypeError, "Cannot include refinement");
}
}
while (argc--) {
rb_funcall(argv[argc], id_append_features, 1, module);
rb_funcall(argv[argc], id_included, 1, module);
}
return module;
}
|
#include? ⇒ Boolean
Returns true
if module is included or prepended in mod or one of mod’s ancestors.
module A
end
class B
include A
end
class C < B
end
B.include?(A) #=> true
C.include?(A) #=> true
A.include?(A) #=> false
1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 |
# File 'class.c', line 1537
VALUE
rb_mod_include_p(VALUE mod, VALUE mod2)
{
VALUE p;
Check_Type(mod2, T_MODULE);
for (p = RCLASS_SUPER(mod); p; p = RCLASS_SUPER(p)) {
if (BUILTIN_TYPE(p) == T_ICLASS && !FL_TEST(p, RICLASS_IS_ORIGIN)) {
if (METACLASS_OF(p) == mod2) return Qtrue;
}
}
return Qfalse;
}
|
#included ⇒ Object (private)
call-seq:
included(othermod)
Callback invoked whenever the receiver is included in another module or class. This should be used in preference to Module.append_features
if your code wants to perform some action when a module is included in another.
module A
def A.included(mod)
puts "#{self} included in #{mod}"
end
end
module Enumerable
include A
end
# => prints "A included in Enumerable"
#included_modules ⇒ Array
Returns the list of modules included or prepended in mod or one of mod’s ancestors.
module Sub
end
module Mixin
prepend Sub
end
module Outer
include Mixin
end
Mixin.included_modules #=> [Sub]
Outer.included_modules #=> [Sub, Mixin]
1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 |
# File 'class.c', line 1501
VALUE
rb_mod_included_modules(VALUE mod)
{
VALUE ary = rb_ary_new();
VALUE p;
VALUE origin = RCLASS_ORIGIN(mod);
for (p = RCLASS_SUPER(mod); p; p = RCLASS_SUPER(p)) {
if (p != origin && RCLASS_ORIGIN(p) == p && BUILTIN_TYPE(p) == T_ICLASS) {
VALUE m = METACLASS_OF(p);
if (RB_TYPE_P(m, T_MODULE))
rb_ary_push(ary, m);
}
}
return ary;
}
|
#initialize_clone(*args) ⇒ Object
:nodoc:
1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 |
# File 'object.c', line 1965
static VALUE
rb_mod_initialize_clone(int argc, VALUE* argv, VALUE clone)
{
VALUE ret, orig, opts;
rb_scan_args(argc, argv, "1:", &orig, &opts);
ret = rb_obj_init_clone(argc, argv, clone);
if (OBJ_FROZEN(orig))
rb_class_name(clone);
return ret;
}
|
#initialize_copy(orig) ⇒ Object
:nodoc:
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 |
# File 'class.c', line 523
VALUE
rb_mod_init_copy(VALUE clone, VALUE orig)
{
switch (BUILTIN_TYPE(clone)) {
case T_CLASS:
case T_ICLASS:
class_init_copy_check(clone, orig);
break;
case T_MODULE:
rb_module_check_initializable(clone);
break;
default:
break;
}
if (!OBJ_INIT_COPY(clone, orig)) return clone;
/* cloned flag is refer at constant inline cache
* see vm_get_const_key_cref() in vm_insnhelper.c
*/
RCLASS_EXT(clone)->cloned = true;
RCLASS_EXT(orig)->cloned = true;
if (!FL_TEST(CLASS_OF(clone), FL_SINGLETON)) {
RBASIC_SET_CLASS(clone, rb_singleton_class_clone(orig));
rb_singleton_class_attached(METACLASS_OF(clone), (VALUE)clone);
}
RCLASS_SET_ALLOCATOR(clone, RCLASS_ALLOCATOR(orig));
copy_tables(clone, orig);
if (RCLASS_M_TBL(orig)) {
struct clone_method_arg arg;
arg.old_klass = orig;
arg.new_klass = clone;
RCLASS_M_TBL_INIT(clone);
rb_id_table_foreach(RCLASS_M_TBL(orig), clone_method_i, &arg);
}
if (RCLASS_ORIGIN(orig) == orig) {
RCLASS_SET_SUPER(clone, RCLASS_SUPER(orig));
}
else {
VALUE p = RCLASS_SUPER(orig);
VALUE orig_origin = RCLASS_ORIGIN(orig);
VALUE prev_clone_p = clone;
VALUE origin_stack = rb_ary_hidden_new(2);
VALUE origin[2];
VALUE clone_p = 0;
long origin_len;
int add_subclass;
VALUE clone_origin;
ensure_origin(clone);
clone_origin = RCLASS_ORIGIN(clone);
while (p && p != orig_origin) {
if (BUILTIN_TYPE(p) != T_ICLASS) {
rb_bug("non iclass between module/class and origin");
}
clone_p = class_alloc(RBASIC(p)->flags, METACLASS_OF(p));
/* We should set the m_tbl right after allocation before anything
* that can trigger GC to avoid clone_p from becoming old and
* needing to fire write barriers. */
RCLASS_SET_M_TBL(clone_p, RCLASS_M_TBL(p));
RCLASS_SET_SUPER(prev_clone_p, clone_p);
prev_clone_p = clone_p;
RCLASS_CONST_TBL(clone_p) = RCLASS_CONST_TBL(p);
RCLASS_SET_ALLOCATOR(clone_p, RCLASS_ALLOCATOR(p));
if (RB_TYPE_P(clone, T_CLASS)) {
RCLASS_SET_INCLUDER(clone_p, clone);
}
add_subclass = TRUE;
if (p != RCLASS_ORIGIN(p)) {
origin[0] = clone_p;
origin[1] = RCLASS_ORIGIN(p);
rb_ary_cat(origin_stack, origin, 2);
}
else if ((origin_len = RARRAY_LEN(origin_stack)) > 1 &&
RARRAY_AREF(origin_stack, origin_len - 1) == p) {
RCLASS_SET_ORIGIN(RARRAY_AREF(origin_stack, (origin_len -= 2)), clone_p);
RICLASS_SET_ORIGIN_SHARED_MTBL(clone_p);
rb_ary_resize(origin_stack, origin_len);
add_subclass = FALSE;
}
if (add_subclass) {
rb_module_add_to_subclasses_list(METACLASS_OF(p), clone_p);
}
p = RCLASS_SUPER(p);
}
if (p == orig_origin) {
if (clone_p) {
RCLASS_SET_SUPER(clone_p, clone_origin);
RCLASS_SET_SUPER(clone_origin, RCLASS_SUPER(orig_origin));
}
copy_tables(clone_origin, orig_origin);
if (RCLASS_M_TBL(orig_origin)) {
struct clone_method_arg arg;
arg.old_klass = orig;
arg.new_klass = clone;
RCLASS_M_TBL_INIT(clone_origin);
rb_id_table_foreach(RCLASS_M_TBL(orig_origin), clone_method_i, &arg);
}
}
else {
rb_bug("no origin for class that has origin");
}
rb_class_update_superclasses(clone);
}
return clone;
}
|
#instance_method(symbol) ⇒ Object
Returns an UnboundMethod
representing the given instance method in mod.
class Interpreter
def do_a() print "there, "; end
def do_d() print "Hello "; end
def do_e() print "!\n"; end
def do_v() print "Dave"; end
Dispatcher = {
"a" => instance_method(:do_a),
"d" => instance_method(:do_d),
"e" => instance_method(:do_e),
"v" => instance_method(:do_v)
}
def interpret(string)
string.each_char {|b| Dispatcher[b].bind(self).call }
end
end
interpreter = Interpreter.new
interpreter.interpret('dave')
produces:
Hello there, Dave!
2183 2184 2185 2186 2187 2188 2189 2190 2191 |
# File 'proc.c', line 2183
static VALUE
rb_mod_instance_method(VALUE mod, VALUE vid)
{
ID id = rb_check_id(&vid);
if (!id) {
rb_method_name_error(mod, vid);
}
return mnew_unbound(mod, id, rb_cUnboundMethod, FALSE);
}
|
#instance_methods(include_super = true) ⇒ Array
Returns an array containing the names of the public and protected instance methods in the receiver. For a module, these are the public and protected methods; for a class, they are the instance (not singleton) methods. If the optional parameter is false
, the methods of any ancestors are not included.
module A
def method1() end
end
class B
include A
def method2() end
end
class C < B
def method3() end
end
A.instance_methods(false) #=> [:method1]
B.instance_methods(false) #=> [:method2]
B.instance_methods(true).include?(:method1) #=> true
C.instance_methods(false) #=> [:method3]
C.instance_methods.include?(:method2) #=> true
Note that method visibility changes in the current class, as well as aliases, are considered as methods of the current class by this method:
class C < B
alias method4 method2
protected :method2
end
C.instance_methods(false).sort #=> [:method2, :method3, :method4]
1888 1889 1890 1891 1892 |
# File 'class.c', line 1888
VALUE
rb_class_instance_methods(int argc, const VALUE *argv, VALUE mod)
{
return class_instance_method_list(argc, argv, mod, 0, ins_methods_i);
}
|
#method_added ⇒ Object (private)
call-seq:
method_added(method_name)
Invoked as a callback whenever an instance method is added to the receiver.
module Chatty
def self.method_added(method_name)
puts "Adding #{method_name.inspect}"
end
def self.some_class_method() end
def some_instance_method() end
end
produces:
Adding :some_instance_method
#method_defined?(symbol, inherit = true) ⇒ Boolean #method_defined?(string, inherit = true) ⇒ Boolean
Returns true
if the named method is defined by mod. If inherit is set, the lookup will also search mod’s ancestors. Public and protected methods are matched. String arguments are converted to symbols.
module A
def method1() end
def protected_method1() end
protected :protected_method1
end
class B
def method2() end
def private_method2() end
private :private_method2
end
class C < B
include A
def method3() end
end
A.method_defined? :method1 #=> true
C.method_defined? "method1" #=> true
C.method_defined? "method2" #=> true
C.method_defined? "method2", true #=> true
C.method_defined? "method2", false #=> false
C.method_defined? "method3" #=> true
C.method_defined? "protected_method1" #=> true
C.method_defined? "method4" #=> false
C.method_defined? "private_method2" #=> false
2043 2044 2045 2046 2047 2048 |
# File 'vm_method.c', line 2043
static VALUE
rb_mod_method_defined(int argc, VALUE *argv, VALUE mod)
{
rb_method_visibility_t visi = check_definition_visibility(mod, argc, argv);
return RBOOL(visi == METHOD_VISI_PUBLIC || visi == METHOD_VISI_PROTECTED);
}
|
#method_removed ⇒ Object (private)
call-seq:
method_removed(method_name)
Invoked as a callback whenever an instance method is removed from the receiver.
module Chatty
def self.method_removed(method_name)
puts "Removing #{method_name.inspect}"
end
def self.some_class_method() end
def some_instance_method() end
class << self
remove_method :some_class_method
end
remove_method :some_instance_method
end
produces:
Removing :some_instance_method
#method_undefined ⇒ Object (private)
call-seq:
method_undefined(method_name)
Invoked as a callback whenever an instance method is undefined from the receiver.
module Chatty
def self.method_undefined(method_name)
puts "Undefining #{method_name.inspect}"
end
def self.some_class_method() end
def some_instance_method() end
class << self
undef_method :some_class_method
end
undef_method :some_instance_method
end
produces:
Undefining :some_instance_method
#class_eval(string[, filename [, lineno]]) ⇒ Object #class_eval {|mod| ... } ⇒ Object #module_eval(string[, filename [, lineno]]) ⇒ Object #module_eval {|mod| ... } ⇒ Object
Evaluates the string or block in the context of mod, except that when a block is given, constant/class variable lookup is not affected. This can be used to add methods to a class. module_eval
returns the result of evaluating its argument. The optional filename and lineno parameters set the text for error messages.
class Thing
end
a = %q{def hello() "Hello there!" end}
Thing.module_eval(a)
puts Thing.new.hello()
Thing.module_eval("invalid code", "dummy", 123)
produces:
Hello there!
dummy:123:in `module_eval': undefined local variable
or method `code' for Thing:Class
2121 2122 2123 2124 2125 |
# File 'vm_eval.c', line 2121
static VALUE
rb_mod_module_eval_internal(int argc, const VALUE *argv, VALUE mod)
{
return specific_eval(argc, argv, mod, FALSE, RB_PASS_CALLED_KEYWORDS);
}
|
#module_exec(arg...) {|var...| ... } ⇒ Object #class_exec(arg...) {|var...| ... } ⇒ Object
Evaluates the given block in the context of the class/module. The method defined in the block will belong to the receiver. Any arguments passed to the method will be passed to the block. This can be used if the block needs to access instance variables.
class Thing
end
Thing.class_exec{
def hello() "Hello there!" end
}
puts Thing.new.hello()
produces:
Hello there!
2155 2156 2157 2158 2159 |
# File 'vm_eval.c', line 2155
static VALUE
rb_mod_module_exec_internal(int argc, const VALUE *argv, VALUE mod)
{
return yield_under(mod, FALSE, argc, argv, RB_PASS_CALLED_KEYWORDS);
}
|
#module_function ⇒ nil (private) #module_function(method_name) ⇒ Object (private) #module_function(method_name, method_name, ...) ⇒ Array (private)
Creates module functions for the named methods. These functions may be called with the module as a receiver, and also become available as instance methods to classes that mix in the module. Module functions are copies of the original, and so may be changed independently. The instance-method versions are made private. If used with no arguments, subsequently defined methods become module functions. String arguments are converted to symbols. If a single argument is passed, it is returned. If no argument is passed, nil is returned. If multiple arguments are passed, the arguments are returned as an array.
module Mod
def one
"This is one"
end
module_function :one
end
class Cls
include Mod
def call_one
one
end
end
Mod.one #=> "This is one"
c = Cls.new
c.call_one #=> "This is one"
module Mod
def one
"This is the new one"
end
end
Mod.one #=> "This is one"
c.call_one #=> "This is the new one"
2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 |
# File 'vm_method.c', line 2765
static VALUE
rb_mod_modfunc(int argc, VALUE *argv, VALUE module)
{
int i;
ID id;
const rb_method_entry_t *me;
if (!RB_TYPE_P(module, T_MODULE)) {
rb_raise(rb_eTypeError, "module_function must be called for modules");
}
if (argc == 0) {
rb_scope_module_func_set();
return Qnil;
}
set_method_visibility(module, argc, argv, METHOD_VISI_PRIVATE);
for (i = 0; i < argc; i++) {
VALUE m = module;
id = rb_to_id(argv[i]);
for (;;) {
me = search_method(m, id, 0);
if (me == 0) {
me = search_method(rb_cObject, id, 0);
}
if (UNDEFINED_METHOD_ENTRY_P(me)) {
rb_print_undef(module, id, METHOD_VISI_UNDEF);
}
if (me->def->type != VM_METHOD_TYPE_ZSUPER) {
break; /* normal case: need not to follow 'super' link */
}
m = RCLASS_SUPER(m);
if (!m)
break;
}
rb_method_entry_set(rb_singleton_class(module), id, me, METHOD_VISI_PUBLIC);
}
if (argc == 1) {
return argv[0];
}
return rb_ary_new_from_values(argc, argv);
}
|
#name ⇒ String
Returns the name of the module mod. Returns nil for anonymous modules.
121 122 123 124 125 126 |
# File 'variable.c', line 121
VALUE
rb_mod_name(VALUE mod)
{
bool permanent;
return classname(mod, &permanent);
}
|
#prepend ⇒ self
Invokes Module.prepend_features on each parameter in reverse order.
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 |
# File 'eval.c', line 1195
static VALUE
rb_mod_prepend(int argc, VALUE *argv, VALUE module)
{
int i;
ID id_prepend_features, id_prepended;
if (BUILTIN_TYPE(module) == T_MODULE && FL_TEST(module, RMODULE_IS_REFINEMENT)) {
rb_raise(rb_eTypeError, "Refinement#prepend has been removed");
}
CONST_ID(id_prepend_features, "prepend_features");
CONST_ID(id_prepended, "prepended");
rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
for (i = 0; i < argc; i++) {
Check_Type(argv[i], T_MODULE);
if (FL_TEST(argv[i], RMODULE_IS_REFINEMENT)) {
rb_raise(rb_eTypeError, "Cannot prepend refinement");
}
}
while (argc--) {
rb_funcall(argv[argc], id_prepend_features, 1, module);
rb_funcall(argv[argc], id_prepended, 1, module);
}
return module;
}
|
#prepend_features(mod) ⇒ Object (private)
When this module is prepended in another, Ruby calls #prepend_features in this module, passing it the receiving module in mod. Ruby’s default implementation is to overlay the constants, methods, and module variables of this module to mod if this module has not already been added to mod or one of its ancestors. See also Module#prepend.
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 |
# File 'eval.c', line 1177
static VALUE
rb_mod_prepend_features(VALUE module, VALUE prepend)
{
if (!CLASS_OR_MODULE_P(prepend)) {
Check_Type(prepend, T_CLASS);
}
rb_prepend_module(prepend, module);
return module;
}
|
#prepended ⇒ Object (private)
call-seq:
prepended(othermod)
The equivalent of included
, but for prepended modules.
module A
def self.prepended(mod)
puts "#{self} prepended to #{mod}"
end
end
module Enumerable
prepend A
end
# => prints "A prepended to Enumerable"
#private ⇒ nil (private) #private(method_name) ⇒ Object (private) #private(method_name, method_name, ...) ⇒ Array (private) #private(array) ⇒ Array (private)
With no arguments, sets the default visibility for subsequently defined methods to private. With arguments, sets the named methods to have private visibility. String arguments are converted to symbols. An Array of Symbols and/or Strings is also accepted. If a single argument is passed, it is returned. If no argument is passed, nil is returned. If multiple arguments are passed, the arguments are returned as an array.
module Mod
def a() end
def b() end
private
def c() end
private :a
end
Mod.private_instance_methods #=> [:a, :c]
Note that to show a private method on RDoc, use :doc:
.
2504 2505 2506 2507 2508 |
# File 'vm_method.c', line 2504
static VALUE
rb_mod_private(int argc, VALUE *argv, VALUE module)
{
return set_visibility(argc, argv, module, METHOD_VISI_PRIVATE);
}
|
#private_class_method(symbol, ...) ⇒ Object #private_class_method(string, ...) ⇒ Object #private_class_method(array) ⇒ Object
Makes existing class methods private. Often used to hide the default constructor new
.
String arguments are converted to symbols. An Array of Symbols and/or Strings is also accepted.
class SimpleSingleton # Not thread safe
private_class_method :new
def SimpleSingleton.create(*args, &block)
@me = new(*args, &block) if ! @me
@me
end
end
2662 2663 2664 2665 2666 2667 |
# File 'vm_method.c', line 2662
static VALUE
rb_mod_private_method(int argc, VALUE *argv, VALUE obj)
{
set_method_visibility(rb_singleton_class(obj), argc, argv, METHOD_VISI_PRIVATE);
return obj;
}
|
#private_constant(symbol, ...) ⇒ Object
Makes a list of existing constants private.
3854 3855 3856 3857 3858 3859 |
# File 'variable.c', line 3854
VALUE
rb_mod_private_constant(int argc, const VALUE *argv, VALUE obj)
{
set_const_visibility(obj, argc, argv, CONST_PRIVATE, CONST_VISIBILITY_MASK);
return obj;
}
|
#private_instance_methods(include_super = true) ⇒ Array
Returns a list of the private instance methods defined in mod. If the optional parameter is false
, the methods of any ancestors are not included.
module Mod
def method1() end
private :method1
def method2() end
end
Mod.instance_methods #=> [:method2]
Mod.private_instance_methods #=> [:method1]
1926 1927 1928 1929 1930 |
# File 'class.c', line 1926
VALUE
rb_class_private_instance_methods(int argc, const VALUE *argv, VALUE mod)
{
return class_instance_method_list(argc, argv, mod, 0, ins_methods_priv_i);
}
|
#private_method_defined?(symbol, inherit = true) ⇒ Boolean #private_method_defined?(string, inherit = true) ⇒ Boolean
Returns true
if the named private method is defined by mod. If inherit is set, the lookup will also search mod’s ancestors. String arguments are converted to symbols.
module A
def method1() end
end
class B
private
def method2() end
end
class C < B
include A
def method3() end
end
A.method_defined? :method1 #=> true
C.private_method_defined? "method1" #=> false
C.private_method_defined? "method2" #=> true
C.private_method_defined? "method2", true #=> true
C.private_method_defined? "method2", false #=> false
C.method_defined? "method2" #=> false
2122 2123 2124 2125 2126 |
# File 'vm_method.c', line 2122
static VALUE
rb_mod_private_method_defined(int argc, VALUE *argv, VALUE mod)
{
return check_definition(mod, argc, argv, METHOD_VISI_PRIVATE);
}
|
#protected ⇒ nil (private) #protected(method_name) ⇒ Object (private) #protected(method_name, method_name, ...) ⇒ Array (private) #protected(array) ⇒ Array (private)
With no arguments, sets the default visibility for subsequently defined methods to protected. With arguments, sets the named methods to have protected visibility. String arguments are converted to symbols. An Array of Symbols and/or Strings is also accepted. If a single argument is passed, it is returned. If no argument is passed, nil is returned. If multiple arguments are passed, the arguments are returned as an array.
If a method has protected visibility, it is callable only where self
of the context is the same as the method. (method definition or instance_eval). This behavior is different from Java’s protected method. Usually private
should be used.
Note that a protected method is slow because it can’t use inline cache.
To show a private method on RDoc, use :doc:
instead of this.
2470 2471 2472 2473 2474 |
# File 'vm_method.c', line 2470
static VALUE
rb_mod_protected(int argc, VALUE *argv, VALUE module)
{
return set_visibility(argc, argv, module, METHOD_VISI_PROTECTED);
}
|
#protected_instance_methods(include_super = true) ⇒ Array
Returns a list of the protected instance methods defined in mod. If the optional parameter is false
, the methods of any ancestors are not included.
1903 1904 1905 1906 1907 |
# File 'class.c', line 1903
VALUE
rb_class_protected_instance_methods(int argc, const VALUE *argv, VALUE mod)
{
return class_instance_method_list(argc, argv, mod, 0, ins_methods_prot_i);
}
|
#protected_method_defined?(symbol, inherit = true) ⇒ Boolean #protected_method_defined?(string, inherit = true) ⇒ Boolean
Returns true
if the named protected method is defined mod. If inherit is set, the lookup will also search mod’s ancestors. String arguments are converted to symbols.
module A
def method1() end
end
class B
protected
def method2() end
end
class C < B
include A
def method3() end
end
A.method_defined? :method1 #=> true
C.protected_method_defined? "method1" #=> false
C.protected_method_defined? "method2" #=> true
C.protected_method_defined? "method2", true #=> true
C.protected_method_defined? "method2", false #=> false
C.method_defined? "method2" #=> true
2158 2159 2160 2161 2162 |
# File 'vm_method.c', line 2158
static VALUE
rb_mod_protected_method_defined(int argc, VALUE *argv, VALUE mod)
{
return check_definition(mod, argc, argv, METHOD_VISI_PROTECTED);
}
|
#public ⇒ nil (private) #public(method_name) ⇒ Object (private) #public(method_name, method_name, ...) ⇒ Array (private) #public(array) ⇒ Array (private)
With no arguments, sets the default visibility for subsequently defined methods to public. With arguments, sets the named methods to have public visibility. String arguments are converted to symbols. An Array of Symbols and/or Strings is also accepted. If a single argument is passed, it is returned. If no argument is passed, nil is returned. If multiple arguments are passed, the arguments are returned as an array.
2438 2439 2440 2441 2442 |
# File 'vm_method.c', line 2438
static VALUE
rb_mod_public(int argc, VALUE *argv, VALUE module)
{
return set_visibility(argc, argv, module, METHOD_VISI_PUBLIC);
}
|
#public_class_method(symbol, ...) ⇒ Object #public_class_method(string, ...) ⇒ Object #public_class_method(array) ⇒ Object
Makes a list of existing class methods public.
String arguments are converted to symbols. An Array of Symbols and/or Strings is also accepted.
2634 2635 2636 2637 2638 2639 |
# File 'vm_method.c', line 2634
static VALUE
rb_mod_public_method(int argc, VALUE *argv, VALUE obj)
{
set_method_visibility(rb_singleton_class(obj), argc, argv, METHOD_VISI_PUBLIC);
return obj;
}
|
#public_constant(symbol, ...) ⇒ Object
Makes a list of existing constants public.
3868 3869 3870 3871 3872 3873 |
# File 'variable.c', line 3868
VALUE
rb_mod_public_constant(int argc, const VALUE *argv, VALUE obj)
{
set_const_visibility(obj, argc, argv, CONST_PUBLIC, CONST_VISIBILITY_MASK);
return obj;
}
|
#public_instance_method(symbol) ⇒ Object
Similar to instance_method, searches public method only.
2200 2201 2202 2203 2204 2205 2206 2207 2208 |
# File 'proc.c', line 2200
static VALUE
rb_mod_public_instance_method(VALUE mod, VALUE vid)
{
ID id = rb_check_id(&vid);
if (!id) {
rb_method_name_error(mod, vid);
}
return mnew_unbound(mod, id, rb_cUnboundMethod, TRUE);
}
|
#public_instance_methods(include_super = true) ⇒ Array
Returns a list of the public instance methods defined in mod. If the optional parameter is false
, the methods of any ancestors are not included.
1941 1942 1943 1944 1945 |
# File 'class.c', line 1941
VALUE
rb_class_public_instance_methods(int argc, const VALUE *argv, VALUE mod)
{
return class_instance_method_list(argc, argv, mod, 0, ins_methods_pub_i);
}
|
#public_method_defined?(symbol, inherit = true) ⇒ Boolean #public_method_defined?(string, inherit = true) ⇒ Boolean
Returns true
if the named public method is defined by mod. If inherit is set, the lookup will also search mod’s ancestors. String arguments are converted to symbols.
module A
def method1() end
end
class B
protected
def method2() end
end
class C < B
include A
def method3() end
end
A.method_defined? :method1 #=> true
C.public_method_defined? "method1" #=> true
C.public_method_defined? "method1", true #=> true
C.public_method_defined? "method1", false #=> true
C.public_method_defined? "method2" #=> false
C.method_defined? "method2" #=> true
2086 2087 2088 2089 2090 |
# File 'vm_method.c', line 2086
static VALUE
rb_mod_public_method_defined(int argc, VALUE *argv, VALUE mod)
{
return check_definition(mod, argc, argv, METHOD_VISI_PUBLIC);
}
|
#refine(mod) { ... } ⇒ Object (private)
Refine mod in the receiver.
Returns a module, where refined methods are defined.
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 |
# File 'eval.c', line 1421
static VALUE
rb_mod_refine(VALUE module, VALUE klass)
{
VALUE refinement;
ID id_refinements, id_activated_refinements,
id_refined_class, id_defined_at;
VALUE refinements, activated_refinements;
rb_thread_t *th = GET_THREAD();
VALUE block_handler = rb_vm_frame_block_handler(th->ec->cfp);
if (block_handler == VM_BLOCK_HANDLER_NONE) {
rb_raise(rb_eArgError, "no block given");
}
if (vm_block_handler_type(block_handler) != block_handler_type_iseq) {
rb_raise(rb_eArgError, "can't pass a Proc as a block to Module#refine");
}
ensure_class_or_module(klass);
CONST_ID(id_refinements, "__refinements__");
refinements = rb_attr_get(module, id_refinements);
if (NIL_P(refinements)) {
refinements = hidden_identity_hash_new();
rb_ivar_set(module, id_refinements, refinements);
}
CONST_ID(id_activated_refinements, "__activated_refinements__");
activated_refinements = rb_attr_get(module, id_activated_refinements);
if (NIL_P(activated_refinements)) {
activated_refinements = hidden_identity_hash_new();
rb_ivar_set(module, id_activated_refinements,
activated_refinements);
}
refinement = rb_hash_lookup(refinements, klass);
if (NIL_P(refinement)) {
VALUE superclass = refinement_superclass(klass);
refinement = rb_refinement_new();
RCLASS_SET_SUPER(refinement, superclass);
RUBY_ASSERT(BUILTIN_TYPE(refinement) == T_MODULE);
FL_SET(refinement, RMODULE_IS_REFINEMENT);
CONST_ID(id_refined_class, "__refined_class__");
rb_ivar_set(refinement, id_refined_class, klass);
CONST_ID(id_defined_at, "__defined_at__");
rb_ivar_set(refinement, id_defined_at, module);
rb_hash_aset(refinements, klass, refinement);
add_activated_refinement(activated_refinements, klass, refinement);
}
rb_yield_refine_block(refinement, activated_refinements);
return refinement;
}
|
#refinements ⇒ Array
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 |
# File 'eval.c', line 1529
static VALUE
mod_refinements(VALUE self)
{
ID id_refinements;
VALUE refinements;
CONST_ID(id_refinements, "__refinements__");
refinements = rb_attr_get(self, id_refinements);
if (NIL_P(refinements)) {
return rb_ary_new();
}
return rb_hash_values(refinements);
}
|
#remove_class_variable(sym) ⇒ Object
Removes the named class variable from the receiver, returning that variable’s value.
class Example
@@var = 99
puts remove_class_variable(:@@var)
p(defined? @@var)
end
produces:
99
nil
4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 |
# File 'variable.c', line 4232
VALUE
rb_mod_remove_cvar(VALUE mod, VALUE name)
{
const ID id = id_for_var_message(mod, name, class, "wrong class variable name %1$s");
st_data_t val;
if (!id) {
goto not_defined;
}
rb_check_frozen(mod);
val = rb_ivar_delete(mod, id, Qundef);
if (!UNDEF_P(val)) {
return (VALUE)val;
}
if (rb_cvar_defined(mod, id)) {
rb_name_err_raise("cannot remove %1$s for %2$s", mod, ID2SYM(id));
}
not_defined:
rb_name_err_raise("class variable %1$s not defined for %2$s",
mod, name);
UNREACHABLE_RETURN(Qundef);
}
|
#remove_const(sym) ⇒ Object (private)
Removes the definition of the given constant, returning that constant’s previous value. If that constant referred to a module, this will not change that module’s name and can lead to confusion.
3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 |
# File 'variable.c', line 3313
VALUE
rb_mod_remove_const(VALUE mod, VALUE name)
{
const ID id = id_for_var(mod, name, a, constant);
if (!id) {
undefined_constant(mod, name);
}
return rb_const_remove(mod, id);
}
|
#remove_method(symbol) ⇒ self #remove_method(string) ⇒ self
Removes the method identified by symbol from the current class. For an example, see Module#undef_method. String arguments are converted to symbols.
1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 |
# File 'vm_method.c', line 1716
static VALUE
rb_mod_remove_method(int argc, VALUE *argv, VALUE mod)
{
int i;
for (i = 0; i < argc; i++) {
VALUE v = argv[i];
ID id = rb_check_id(&v);
if (!id) {
rb_name_err_raise("method `%1$s' not defined in %2$s",
mod, v);
}
remove_method(mod, id);
}
return mod;
}
|
#ruby2_keywords(method_name, ...) ⇒ nil (private)
For the given method names, marks the method as passing keywords through a normal argument splat. This should only be called on methods that accept an argument splat (*args
) but not explicit keywords or a keyword splat. It marks the method such that if the method is called with keyword arguments, the final hash argument is marked with a special flag such that if it is the final element of a normal argument splat to another method call, and that method call does not include explicit keywords or a keyword splat, the final element is interpreted as keywords. In other words, keywords will be passed through the method to other methods.
This should only be used for methods that delegate keywords to another method, and only for backwards compatibility with Ruby versions before 3.0. See www.ruby-lang.org/en/news/2019/12/12/separation-of-positional-and-keyword-arguments-in-ruby-3-0/ for details on why ruby2_keywords
exists and when and how to use it.
This method will probably be removed at some point, as it exists only for backwards compatibility. As it does not exist in Ruby versions before 2.7, check that the module responds to this method before calling it:
module Mod
def foo(meth, *args, &block)
send(:"do_#{meth}", *args, &block)
end
ruby2_keywords(:foo) if respond_to?(:ruby2_keywords, true)
end
However, be aware that if the ruby2_keywords
method is removed, the behavior of the foo
method using the above approach will change so that the method does not pass through keywords.
2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 |
# File 'vm_method.c', line 2546
static VALUE
rb_mod_ruby2_keywords(int argc, VALUE *argv, VALUE module)
{
int i;
VALUE origin_class = RCLASS_ORIGIN(module);
rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
rb_check_frozen(module);
for (i = 0; i < argc; i++) {
VALUE v = argv[i];
ID name = rb_check_id(&v);
rb_method_entry_t *me;
VALUE defined_class;
if (!name) {
rb_print_undef_str(module, v);
}
me = search_method(origin_class, name, &defined_class);
if (!me && RB_TYPE_P(module, T_MODULE)) {
me = search_method(rb_cObject, name, &defined_class);
}
if (UNDEFINED_METHOD_ENTRY_P(me) ||
UNDEFINED_REFINED_METHOD_P(me->def)) {
rb_print_undef(module, name, METHOD_VISI_UNDEF);
}
if (module == defined_class || origin_class == defined_class) {
switch (me->def->type) {
case VM_METHOD_TYPE_ISEQ:
if (ISEQ_BODY(me->def->body.iseq.iseqptr)->param.flags.has_rest &&
!ISEQ_BODY(me->def->body.iseq.iseqptr)->param.flags.has_kw &&
!ISEQ_BODY(me->def->body.iseq.iseqptr)->param.flags.has_kwrest) {
ISEQ_BODY(me->def->body.iseq.iseqptr)->param.flags.ruby2_keywords = 1;
rb_clear_method_cache(module, name);
}
else {
rb_warn("Skipping set of ruby2_keywords flag for %s (method accepts keywords or method does not accept argument splat)", rb_id2name(name));
}
break;
case VM_METHOD_TYPE_BMETHOD: {
VALUE procval = me->def->body.bmethod.proc;
if (vm_block_handler_type(procval) == block_handler_type_proc) {
procval = vm_proc_to_block_handler(VM_BH_TO_PROC(procval));
}
if (vm_block_handler_type(procval) == block_handler_type_iseq) {
const struct rb_captured_block *captured = VM_BH_TO_ISEQ_BLOCK(procval);
const rb_iseq_t *iseq = rb_iseq_check(captured->code.iseq);
if (ISEQ_BODY(iseq)->param.flags.has_rest &&
!ISEQ_BODY(iseq)->param.flags.has_kw &&
!ISEQ_BODY(iseq)->param.flags.has_kwrest) {
ISEQ_BODY(iseq)->param.flags.ruby2_keywords = 1;
rb_clear_method_cache(module, name);
}
else {
rb_warn("Skipping set of ruby2_keywords flag for %s (method accepts keywords or method does not accept argument splat)", rb_id2name(name));
}
break;
}
}
/* fallthrough */
default:
rb_warn("Skipping set of ruby2_keywords flag for %s (method not defined in Ruby)", rb_id2name(name));
break;
}
}
else {
rb_warn("Skipping set of ruby2_keywords flag for %s (can only set in method defining module)", rb_id2name(name));
}
}
return Qnil;
}
|
#set_temporary_name(string) ⇒ self #set_temporary_name(nil) ⇒ self
Sets the temporary name of the module. This name is reflected in introspection of the module and the values that are related to it, such as instances, constants, and methods.
The name should be nil
or non-empty string that is not a valid constant name (to avoid confusing between permanent and temporary names).
The method can be useful to distinguish dynamically generated classes and modules without assigning them to constants.
If the module is given a permanent name by assigning it to a constant, the temporary name is discarded. A temporary name can’t be assigned to modules that have a permanent name.
If the given name is nil
, the module becomes anonymous again.
Example:
m = Module.new # => #<Module:0x0000000102c68f38>
m.name #=> nil
m.set_temporary_name("fake_name") # => fake_name
m.name #=> "fake_name"
m.set_temporary_name(nil) # => #<Module:0x0000000102c68f38>
m.name #=> nil
c = Class.new
c.set_temporary_name("MyClass(with description)")
c.new # => #<MyClass(with description):0x0....>
c::M = m
c::M.name #=> "MyClass(with description)::M"
# Assigning to a constant replaces the name with a permanent one
C = c
C.name #=> "C"
C::M.name #=> "C::M"
c.new # => #<C:0x0....>
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 |
# File 'variable.c', line 282
VALUE
rb_mod_set_temporary_name(VALUE mod, VALUE name)
{
// We don't allow setting the name if the classpath is already permanent:
if (RCLASS_EXT(mod)->permanent_classpath) {
rb_raise(rb_eRuntimeError, "can't change permanent name");
}
if (NIL_P(name)) {
// Set the temporary classpath to NULL (anonymous):
RB_VM_LOCK_ENTER();
set_sub_temporary_name(mod, 0);
RB_VM_LOCK_LEAVE();
}
else {
// Ensure the name is a string:
StringValue(name);
if (RSTRING_LEN(name) == 0) {
rb_raise(rb_eArgError, "empty class/module name");
}
if (is_constant_path(name)) {
rb_raise(rb_eArgError, "the temporary name must not be a constant path to avoid confusion");
}
name = rb_str_new_frozen(name);
// Set the temporary classpath to the given name:
RB_VM_LOCK_ENTER();
set_sub_temporary_name(mod, name);
RB_VM_LOCK_LEAVE();
}
return mod;
}
|
#singleton_class? ⇒ Boolean
Returns true
if mod is a singleton class or false
if it is an ordinary class or module.
class C
end
C.singleton_class? #=> false
C.singleton_class.singleton_class? #=> true
3049 3050 3051 3052 3053 |
# File 'object.c', line 3049
static VALUE
rb_mod_singleton_p(VALUE klass)
{
return RBOOL(RB_TYPE_P(klass, T_CLASS) && FL_TEST(klass, FL_SINGLETON));
}
|
#to_s ⇒ String Also known as: inspect
Returns a string representing this module or class. For basic classes and modules, this is the name. For singletons, we show information on the thing we’re attached to as well.
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 |
# File 'object.c', line 1709
VALUE
rb_mod_to_s(VALUE klass)
{
ID id_defined_at;
VALUE refined_class, defined_at;
if (FL_TEST(klass, FL_SINGLETON)) {
VALUE s = rb_usascii_str_new2("#<Class:");
VALUE v = RCLASS_ATTACHED_OBJECT(klass);
if (CLASS_OR_MODULE_P(v)) {
rb_str_append(s, rb_inspect(v));
}
else {
rb_str_append(s, rb_any_to_s(v));
}
rb_str_cat2(s, ">");
return s;
}
refined_class = rb_refinement_module_get_refined_class(klass);
if (!NIL_P(refined_class)) {
VALUE s = rb_usascii_str_new2("#<refinement:");
rb_str_concat(s, rb_inspect(refined_class));
rb_str_cat2(s, "@");
CONST_ID(id_defined_at, "__defined_at__");
defined_at = rb_attr_get(klass, id_defined_at);
rb_str_concat(s, rb_inspect(defined_at));
rb_str_cat2(s, ">");
return s;
}
return rb_class_name(klass);
}
|
#undef_method(symbol) ⇒ self #undef_method(string) ⇒ self
Prevents the current class from responding to calls to the named method. Contrast this with remove_method
, which deletes the method from the particular class; Ruby will still search superclasses and mixed-in modules for a possible receiver. String arguments are converted to symbols.
class Parent
def hello
puts "In parent"
end
end
class Child < Parent
def hello
puts "In child"
end
end
c = Child.new
c.hello
class Child
remove_method :hello # remove from child, still in parent
end
c.hello
class Child
undef_method :hello # prevent any calls to 'hello'
end
c.hello
produces:
In child
In parent
prog.rb:23: undefined method `hello' for #<Child:0x401b3bb4> (NoMethodError)
1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 |
# File 'vm_method.c', line 1961
static VALUE
rb_mod_undef_method(int argc, VALUE *argv, VALUE mod)
{
int i;
for (i = 0; i < argc; i++) {
VALUE v = argv[i];
ID id = rb_check_id(&v);
if (!id) {
rb_method_name_error(mod, v);
}
rb_undef(mod, id);
}
return mod;
}
|
#undefined_instance_methods ⇒ Array
Returns a list of the undefined instance methods defined in mod. The undefined methods of any ancestors are not included.
1955 1956 1957 1958 1959 1960 |
# File 'class.c', line 1955
VALUE
rb_class_undefined_instance_methods(VALUE mod)
{
VALUE include_super = Qfalse;
return class_instance_method_list(1, &include_super, mod, 0, ins_methods_undef_i);
}
|
#using ⇒ self (private)
Import class refinements from module into the current class or module definition.
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 |
# File 'eval.c', line 1489
static VALUE
mod_using(VALUE self, VALUE module)
{
rb_control_frame_t *prev_cfp = previous_frame(GET_EC());
if (prev_frame_func()) {
rb_raise(rb_eRuntimeError,
"Module#using is not permitted in methods");
}
if (prev_cfp && prev_cfp->self != self) {
rb_raise(rb_eRuntimeError, "Module#using is not called on self");
}
if (rb_block_given_p()) {
ignored_block(module, "Module#");
}
rb_using_module(rb_vm_cref_replace_with_duplicated_cref(), module);
return self;
}
|