Class: Module
Relationships & Source Files | |
Extension / Inclusion / Inheritance Descendants | |
Subclasses:
|
|
Inherits: | Object |
Defined in: | class.c, eval.c, load.c, object.c, proc.c, variable.c, vm_eval.c, vm_method.c |
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_function.)
In the descriptions that follow, the parameter sym refers to a symbol, which is either a quoted string or a ::Symbol (such as :name
).
module Mod
include Math
CONST = 1
def meth
# ...
end
end
Mod.class #=> Module
Mod.constants #=> [:CONST, :PI, :E]
Mod.instance_methods #=> [:meth]
Class Method Summary
-
.constants ⇒ Array
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. -
.new ⇒ mod
constructor
Creates a new anonymous module.
-
.used_modules ⇒ Array
Returns an array of all modules used in the current scope.
Instance Attribute Summary
-
#singleton_class? ⇒ Boolean
readonly
Returns
true
if mod is a singleton class orfalse
if it is an ordinary class or module.
Instance Method Summary
-
#<(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
. -
#==(other) ⇒ Boolean
Alias for Object#eql?.
-
#===(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) ⇒ self
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).
-
#attr(name, ...) ⇒ nil
The first form is equivalent to #attr_reader.
-
#attr_accessor(symbol, ...) ⇒ nil
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(symbol, ...) ⇒ nil
Creates instance variables and corresponding methods that return the value of each instance variable.
-
#attr_writer(symbol, ...) ⇒ nil
Creates an accessor method to allow assignment to the attribute symbol
.id2name
. -
#autoload(module, filename) ⇒ nil
Registers filename to be loaded (using Kernel.require) the first time that module (which may be a ::String or a symbol) is accessed in the namespace of mod.
-
#autoload?(name) ⇒ String?
Returns filename to be loaded if name is registered as #autoload in the namespace of mod.
-
#class_eval(string [, filename [, lineno]]) ⇒ Object
(also: #module_eval)
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(arg...) {|var...| ... } ⇒ Object
(also: #module_exec)
Evaluates the given block in the context of the class/module.
-
#class_variable_defined?(symbol) ⇒ Boolean
Returns
true
if the given class variable is defined in obj. -
#class_variable_get(symbol) ⇒ Object
Returns the value of the given class variable (or throws a ::NameError exception).
-
#class_variable_set(symbol, obj) ⇒ 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_defined?(sym, inherit = true) ⇒ Boolean
Says whether mod or its ancestors have a constant with the given name:
-
#const_get(sym, inherit = true) ⇒ 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(sym, obj) ⇒ Object
Sets the named constant to the given object, returning that object.
-
#constants(inherit = true) ⇒ Array
Returns an array of the names of the constants accessible in mod.
-
#define_method(symbol, method) ⇒ Symbol
Defines an instance method in the receiver.
-
#deprecate_constant(symbol, ...) ⇒ mod
Makes a list of existing constants deprecated.
-
#freeze ⇒ mod
Prevents further modifications to mod.
-
#include(module, ...) ⇒ self
Invokes #append_features on each parameter in reverse order.
-
#include?(module) ⇒ Boolean
Returns
true
if module is included in mod or one of mod's ancestors. -
#included_modules ⇒ Array
Returns the list of modules included in mod.
-
#inspect ⇒ String
Alias for #to_s.
-
#instance_method(symbol) ⇒ unbound_method
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_defined?(symbol) ⇒ Boolean
Returns
true
if the named method is defined by mod (or its included modules and, if mod is a class, its ancestors). -
#module_eval(string [, filename [, lineno]]) ⇒ Object
Alias for #class_eval.
-
#module_exec(arg...) {|var...| ... } ⇒ Object
Alias for #class_exec.
-
#name ⇒ String
Returns the name of the module mod.
-
#prepend(module, ...) ⇒ self
Invokes #prepend_features on each parameter in reverse order.
-
#private_class_method(symbol, ...) ⇒ mod
Makes existing class methods private.
-
#private_constant(symbol, ...) ⇒ mod
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?(symbol) ⇒ Boolean
Returns
true
if the named private method is defined by _ mod_ (or its included modules and, if mod is a class, its ancestors). -
#protected_instance_methods(include_super = true) ⇒ Array
Returns a list of the protected instance methods defined in mod.
-
#protected_method_defined?(symbol) ⇒ Boolean
Returns
true
if the named protected method is defined by mod (or its included modules and, if mod is a class, its ancestors). -
#public_class_method(symbol, ...) ⇒ mod
Makes a list of existing class methods public.
-
#public_constant(symbol, ...) ⇒ mod
Makes a list of existing constants public.
-
#public_instance_method(symbol) ⇒ unbound_method
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?(symbol) ⇒ Boolean
Returns
true
if the named public method is defined by mod (or its included modules and, if mod is a class, its ancestors). -
#remove_class_variable(sym) ⇒ Object
Removes the definition of the sym, returning that constant's value.
-
#remove_method(symbol) ⇒ self
Removes the method identified by symbol from the current class.
-
#to_s ⇒ String
(also: #inspect)
Returns a string representing this module or class.
-
#undef_method(symbol) ⇒ self
Prevents the current class from responding to calls to the named method.
-
#append_features(mod) ⇒ mod
private
When this module is included in another, Ruby calls
append_features
in this module, passing it the receiving module in mod. -
#extend_object(obj) ⇒ Object
private
Extends the specified object by adding this module's constants and methods (which are added as singleton methods).
-
#extended(othermod)
private
The equivalent of #included, but for extended modules.
-
#included(othermod)
private
Callback invoked whenever the receiver is included in another module or class.
-
#method_added(method_name)
private
Invoked as a callback whenever an instance method is added to the receiver.
-
#method_removed(method_name)
private
Invoked as a callback whenever an instance method is removed from the receiver.
- #method_undefined private
-
#module_function(symbol, ...) ⇒ self
private
Creates module functions for the named methods.
-
#prepend_features(mod) ⇒ mod
private
When this module is prepended in another, Ruby calls
prepend_features
in this module, passing it the receiving module in mod. -
#prepended(othermod)
private
The equivalent of #included, but for prepended modules.
-
#private ⇒ self
private
With no arguments, sets the default visibility for subsequently defined methods to private.
-
#protected ⇒ self
private
With no arguments, sets the default visibility for subsequently defined methods to protected.
-
#public ⇒ self
private
With no arguments, sets the default visibility for subsequently defined methods to public.
-
#refine(mod) ⇒ Module
private
Refine mod in the receiver.
-
#remove_const(sym) ⇒ Object
private
Removes the definition of the given constant, returning that constant's previous value.
-
#using(module) ⇒ self
private
Import class refinements from module into the current class or module definition.
- #initialize_clone(orig) Internal use only
- #initialize_copy(orig) Internal use only
Constructor Details
.new ⇒ mod
.new {|mod| ... } ⇒ mod
mod
.new {|mod| ... } ⇒ mod
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.
# File 'object.c', line 1973
static VALUE rb_mod_initialize(VALUE module) { if (rb_block_given_p()) { rb_mod_module_exec(1, &module, module); } return Qnil; }
Class Method Details
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
.
# File 'eval.c', line 368
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"
# File 'eval.c', line 329
static VALUE rb_mod_nesting(void) { 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
# File 'eval.c', line 1560
static VALUE rb_mod_s_used_modules(void) { 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); }
Instance Attribute Details
#singleton_class? ⇒ Boolean
(readonly)
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
# File 'object.c', line 2859
static VALUE rb_mod_singleton_p(VALUE klass) { if (RB_TYPE_P(klass, T_CLASS) && FL_TEST(klass, FL_SINGLETON)) return Qtrue; return Qfalse; }
Instance Method Details
#<(other) ⇒ true
, ...
Returns true if mod is a subclass 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”.)
# File 'object.c', line 1854
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”.)
# File 'object.c', line 1826
VALUE rb_class_inherited_p(VALUE mod, VALUE arg) { if (mod == arg) return Qtrue; 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.
# File 'object.c', line 1914
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
Alias for Object#eql?. 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 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
#===(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.
# File 'object.c', line 1800
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 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”.)
# File 'object.c', line 1895
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”.)
# File 'object.c', line 1874
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) ⇒ self
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
def exit(code=0)
puts "Exiting with code #{code}"
orig_exit(code)
end
end
include Mod
exit(99)
produces:
Exiting with code 99
# File 'vm_method.c', line 1618
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); } rb_alias(mod, rb_to_id(newname), oldid); return mod; }
#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]
# File 'class.c', line 1084
VALUE rb_mod_ancestors(VALUE mod) { VALUE p, ary = rb_ary_new(); for (p = mod; p; p = RCLASS_SUPER(p)) { if (BUILTIN_TYPE(p) == T_ICLASS) { rb_ary_push(ary, RBASIC(p)->klass); } else if (p == RCLASS_ORIGIN(p)) { rb_ary_push(ary, p); } } return ary; }
#append_features(mod) ⇒ mod
(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 #include.
# File 'eval.c', line 1172
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, ...) ⇒ nil
#attr(name, true) ⇒ nil
#attr(name, false) ⇒ nil
nil
#attr(name, true) ⇒ nil
#attr(name, false) ⇒ nil
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.
# File 'object.c', line 2316
VALUE rb_mod_attr(int argc, VALUE *argv, VALUE klass) { if (argc == 2 && (argv[1] == Qtrue || argv[1] == Qfalse)) { rb_warning("optional boolean argument is obsoleted"); rb_attr(klass, id_for_attr(klass, argv[0]), 1, RTEST(argv[1]), TRUE); return Qnil; } return rb_mod_attr_reader(argc, argv, klass); }
#attr_accessor(symbol, ...) ⇒ nil
#attr_accessor(string, ...) ⇒ nil
nil
#attr_accessor(string, ...) ⇒ nil
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.
module Mod
attr_accessor(:one, :two)
end
Mod.instance_methods.sort #=> [:one, :one=, :two, :two=]
# File 'object.c', line 2365
static VALUE rb_mod_attr_accessor(int argc, VALUE *argv, VALUE klass) { int i; for (i=0; i<argc; i++) { rb_attr(klass, id_for_attr(klass, argv[i]), TRUE, TRUE, TRUE); } return Qnil; }
#attr_reader(symbol, ...) ⇒ nil
#attr(symbol, ...) ⇒ nil
#attr_reader(string, ...) ⇒ nil
#attr(string, ...) ⇒ nil
nil
#attr(symbol, ...) ⇒ nil
#attr_reader(string, ...) ⇒ nil
#attr(string, ...) ⇒ nil
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.
# File 'object.c', line 2291
static VALUE rb_mod_attr_reader(int argc, VALUE *argv, VALUE klass) { int i; for (i=0; i<argc; i++) { rb_attr(klass, id_for_attr(klass, argv[i]), TRUE, FALSE, TRUE); } return Qnil; }
#attr_writer(symbol, ...) ⇒ nil
#attr_writer(string, ...) ⇒ nil
nil
#attr_writer(string, ...) ⇒ nil
Creates an accessor method to allow assignment to the attribute symbol.id2name
. ::String arguments are converted to symbols.
# File 'object.c', line 2337
static VALUE rb_mod_attr_writer(int argc, VALUE *argv, VALUE klass) { int i; for (i=0; i<argc; i++) { rb_attr(klass, id_for_attr(klass, argv[i]), FALSE, TRUE, TRUE); } return Qnil; }
#autoload(module, filename) ⇒ nil
Registers filename to be loaded (using Kernel.require) the first time that module (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"
# File 'load.c', line 1099
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) ⇒ String?
# File 'load.c', line 1122
static VALUE rb_mod_autoload_p(VALUE mod, VALUE sym) { ID id = rb_check_id(&sym); if (!id) { return Qnil; } return rb_autoload_p(mod, id); }
#class_eval(string [, filename [, lineno]]) ⇒ Object
#class_eval {|mod| ... } ⇒ Object
#module_eval(string [, filename [, lineno]]) ⇒ Object
#module_eval {|mod| ... } ⇒ Object
Also known as: #module_eval
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
# File 'vm_eval.c', line 1754
VALUE rb_mod_module_eval(int argc, const VALUE *argv, VALUE mod) { return specific_eval(argc, argv, mod, mod); }
Also known as: #module_exec
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!
# File 'vm_eval.c', line 1782
VALUE rb_mod_module_exec(int argc, const VALUE *argv, VALUE mod) { return yield_under(mod, mod, argc, argv); }
#class_variable_defined?(symbol) ⇒ Boolean
#class_variable_defined?(string) ⇒ Boolean
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
# File 'object.c', line 2835
static VALUE rb_mod_cvar_defined(VALUE obj, VALUE iv) { ID id = id_for_var(obj, iv, a, class); if (!id) { return Qfalse; } return rb_cvar_defined(obj, id); }
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
# File 'object.c', line 2778
static VALUE rb_mod_cvar_get(VALUE obj, VALUE iv) { ID id = id_for_var(obj, iv, a, class); if (!id) { rb_name_err_raise("uninitialized class variable %1$s in %2$s", obj, iv); } return rb_cvar_get(obj, id); }
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
# File 'object.c', line 2810
static VALUE rb_mod_cvar_set(VALUE obj, VALUE iv, VALUE val) { ID id = id_for_var(obj, iv, a, 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]
# File 'variable.c', line 3072
VALUE rb_mod_class_variables(int argc, const VALUE *argv, VALUE mod) { VALUE inherit; st_table *tbl; if (argc == 0) { inherit = Qtrue; } else { rb_scan_args(argc, argv, "01", &inherit); } if (RTEST(inherit)) { tbl = mod_cvar_of(mod, 0); } else { tbl = mod_cvar_at(mod, 0); } return cvar_list(tbl); }
#const_defined?(sym, inherit = true) ⇒ Boolean
#const_defined?(str, inherit = true) ⇒ Boolean
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
# File 'object.c', line 2574
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) { wrong_name: rb_name_err_raise(wrong_constant_name, mod, 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 (!ISUPPER(*pbeg) || !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 (RTEST(recur)) { if (!rb_const_defined(mod, id)) return Qfalse; mod = rb_const_get(mod, id); } else { if (!rb_const_defined_at(mod, id)) return Qfalse; mod = rb_const_get_at(mod, id); } recur = Qfalse; 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; }
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
# File 'object.c', line 2416
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) { wrong_name: rb_name_err_raise(wrong_constant_name, mod, 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 (!ISUPPER(*pbeg) || !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; } mod = RTEST(recur) ? rb_const_get(mod, id) : rb_const_get_at(mod, id); } return mod; }
#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 #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
# File 'variable.c', line 1793
VALUE rb_mod_const_missing(VALUE klass, VALUE name) { rb_vm_pop_cfunc_frame(); uninitialized_constant(klass, name); UNREACHABLE; }
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
# File 'object.c', line 2523
static VALUE rb_mod_const_set(VALUE mod, VALUE name, VALUE value) { ID id = id_for_setter(mod, name, const, wrong_constant_name); if (!id) id = rb_intern_str(name); rb_const_set(mod, id, value); return value; }
#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 #const_defined?.
# File 'variable.c', line 2504
VALUE rb_mod_constants(int argc, const VALUE *argv, VALUE mod) { VALUE inherit; if (argc == 0) { inherit = Qtrue; } else { rb_scan_args(argc, argv, "01", &inherit); } if (RTEST(inherit)) { return rb_const_list(rb_mod_const_of(mod, 0)); } else { return rb_local_constants(mod); } }
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. 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!" }
end
class B < A
define_method(:, instance_method(:fred))
end
a = B.new
a.
a.wilma
a.create_method(:betty) { p self }
a.betty
produces:
In Fred
Charge it!
#<B:0x401b39e8>
# File 'proc.c', line 1889
static VALUE rb_mod_define_method(int argc, VALUE *argv, VALUE mod) { ID id; VALUE body; VALUE name; 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; int is_method = FALSE; if (cref) { scope_visi = CREF_SCOPE_VISI(cref); } rb_check_arity(argc, 1, 2); name = argv[0]; id = rb_check_id(&name); if (argc == 1) { #if PROC_NEW_REQUIRES_BLOCK body = rb_block_lambda(); #else const rb_execution_context_t *ec = GET_EC(); VALUE block_handler = rb_vm_frame_block_handler(ec->cfp); if (block_handler == VM_BLOCK_HANDLER_NONE) rb_raise(rb_eArgError, proc_without_block); switch (vm_block_handler_type(block_handler)) { case block_handler_type_proc: body = VM_BH_TO_PROC(block_handler); break; case block_handler_type_symbol: body = rb_sym_to_proc(VM_BH_TO_SYMBOL(block_handler)); break; case block_handler_type_iseq: case block_handler_type_ifunc: body = rb_vm_make_lambda(ec, VM_BH_TO_CAPT_BLOCK(block_handler), rb_cProc); } #endif } else { body = argv[1]; if (rb_obj_is_method(body)) { is_method = TRUE; } else if (rb_obj_is_proc(body)) { is_method = FALSE; } else { rb_raise(rb_eTypeError, "wrong argument type %s (expected Proc/Method)", rb_obj_classname(body)); } } if (!id) id = rb_to_id(name); if (is_method) { struct METHOD *method = (struct METHOD *)DATA_PTR(body); if (method->me->owner != mod && !RB_TYPE_P(method->me->owner, T_MODULE) && !RTEST(rb_class_inherited_p(mod, method->me->owner))) { if (FL_TEST(method->me->owner, FL_SINGLETON)) { rb_raise(rb_eTypeError, "can't bind singleton method to a different class"); } else { rb_raise(rb_eTypeError, "bind argument must be a subclass of % "PRIsVALUE, method->me->owner); } } rb_method_entry_set(mod, id, method->me, scope_visi->method_visi); if (scope_visi->module_func) { rb_method_entry_set(rb_singleton_class(mod), id, method->me, METHOD_VISI_PUBLIC); } RB_GC_GUARD(body); } else { VALUE procval = proc_dup(body); if (vm_proc_iseq(procval) != NULL) { rb_proc_t *proc; GetProcPtr(procval, proc); proc->is_lambda = TRUE; proc->is_from_method = TRUE; } rb_add_method(mod, id, VM_METHOD_TYPE_BMETHOD, (void *)procval, scope_visi->method_visi); if (scope_visi->module_func) { rb_add_method(rb_singleton_class(mod), id, VM_METHOD_TYPE_BMETHOD, (void *)body, METHOD_VISI_PUBLIC); } } return ID2SYM(id); }
#deprecate_constant(symbol, ...) ⇒ mod
Makes a list of existing constants deprecated.
# File 'variable.c', line 2847
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
# File 'eval.c', line 1632
static VALUE rb_mod_extend_object(VALUE mod, VALUE obj) { rb_extend_object(obj, mod); return obj; }
#extended(othermod) (private)
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 ⇒ mod
Prevents further modifications to mod.
This method returns self.
# File 'object.c', line 1783
static VALUE rb_mod_freeze(VALUE mod) { rb_class_name(mod); return rb_obj_freeze(mod); }
#include(module, ...) ⇒ self
Invokes #append_features on each parameter in reverse order.
# File 'eval.c', line 1190
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"); rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS); for (i = 0; i < argc; i++) Check_Type(argv[i], T_MODULE); while (argc--) { rb_funcall(argv[argc], id_append_features, 1, module); rb_funcall(argv[argc], id_included, 1, module); } return module; }
#include?(module) ⇒ Boolean
Returns true
if module is included 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
# File 'class.c', line 1052
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) { if (RBASIC(p)->klass == mod2) return Qtrue; } } return Qfalse; }
#included(othermod) (private)
Callback invoked whenever the receiver is included in another module or class. This should be used in preference to #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"
# File 'object.c', line 1123
static VALUE rb_obj_dummy(void) { return Qnil; }
#included_modules ⇒ Array
Returns the list of modules included in mod.
module Mixin
end
module Outer
include Mixin
end
Mixin.included_modules #=> []
Outer.included_modules #=> [Mixin]
# File 'class.c', line 1016
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 && BUILTIN_TYPE(p) == T_ICLASS) { VALUE m = RBASIC(p)->klass; if (RB_TYPE_P(m, T_MODULE)) rb_ary_push(ary, m); } } return ary; }
#initialize_clone(orig)
# File 'object.c', line 1983
static VALUE rb_mod_initialize_clone(VALUE clone, VALUE orig) { VALUE ret; ret = rb_obj_init_dup_clone(clone, orig); if (OBJ_FROZEN(orig)) rb_class_name(clone); return ret; }
#initialize_copy(orig)
# File 'class.c', line 313
VALUE rb_mod_init_copy(VALUE clone, VALUE orig) { if (RB_TYPE_P(clone, T_CLASS)) { class_init_copy_check(clone, orig); } if (!OBJ_INIT_COPY(clone, orig)) return clone; if (!FL_TEST(CLASS_OF(clone), FL_SINGLETON)) { RBASIC_SET_CLASS(clone, rb_singleton_class_clone(orig)); rb_singleton_class_attached(RBASIC(clone)->klass, (VALUE)clone); } RCLASS_SET_SUPER(clone, RCLASS_SUPER(orig)); RCLASS_EXT(clone)->allocator = RCLASS_EXT(orig)->allocator; if (RCLASS_IV_TBL(clone)) { st_free_table(RCLASS_IV_TBL(clone)); RCLASS_IV_TBL(clone) = 0; } if (RCLASS_CONST_TBL(clone)) { rb_free_const_table(RCLASS_CONST_TBL(clone)); RCLASS_CONST_TBL(clone) = 0; } RCLASS_M_TBL(clone) = 0; if (RCLASS_IV_TBL(orig)) { st_data_t id; RCLASS_IV_TBL(clone) = rb_st_copy(clone, RCLASS_IV_TBL(orig)); CONST_ID(id, "__tmp_classpath__"); st_delete(RCLASS_IV_TBL(clone), &id, 0); CONST_ID(id, "__classpath__"); st_delete(RCLASS_IV_TBL(clone), &id, 0); CONST_ID(id, "__classid__"); st_delete(RCLASS_IV_TBL(clone), &id, 0); } if (RCLASS_CONST_TBL(orig)) { struct clone_const_arg arg; arg.tbl = RCLASS_CONST_TBL(clone) = rb_id_table_create(0); arg.klass = clone; rb_id_table_foreach(RCLASS_CONST_TBL(orig), clone_const_i, &arg); } 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); } return clone; }
Alias for #to_s.
#instance_method(symbol) ⇒ unbound_method
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!
# File 'proc.c', line 1827
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(mod, Qundef, 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
# File 'class.c', line 1240
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(method_name) (private)
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) ⇒ Boolean
#method_defined?(string) ⇒ Boolean
Boolean
#method_defined?(string) ⇒ Boolean
Returns true
if the named method is defined by mod (or its included modules and, if mod is a class, its 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? "method3" #=> true
C.method_defined? "protected_method1" #=> true
C.method_defined? "method4" #=> false
C.method_defined? "private_method2" #=> false
# File 'vm_method.c', line 1312
static VALUE rb_mod_method_defined(VALUE mod, VALUE mid) { ID id = rb_check_id(&mid); if (!id || !rb_method_boundp(mod, id, 1)) { return Qfalse; } return Qtrue; }
#method_removed(method_name) (private)
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 (private)
[ GitHub ]Alias for #class_eval.
Alias for #class_exec.
#module_function(symbol, ...) ⇒ self
(private)
#module_function(string, ...) ⇒ self
self
(private)
#module_function(string, ...) ⇒ self
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.
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"
# File 'vm_method.c', line 1855
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 module; } 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); } return module; }
#name ⇒ String
Returns the name of the module mod. Returns nil for anonymous modules.
# File 'variable.c', line 229
VALUE rb_mod_name(VALUE mod) { int permanent; VALUE path = classname(mod, &permanent); if (!NIL_P(path)) return rb_str_dup(path); return path; }
#prepend(module, ...) ⇒ self
Invokes #prepend_features on each parameter in reverse order.
# File 'eval.c', line 1239
static VALUE rb_mod_prepend(int argc, VALUE *argv, VALUE module) { int i; ID id_prepend_features, id_prepended; 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); while (argc--) { rb_funcall(argv[argc], id_prepend_features, 1, module); rb_funcall(argv[argc], id_prepended, 1, module); } return module; }
#prepend_features(mod) ⇒ mod
(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 #prepend.
# File 'eval.c', line 1221
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(othermod) (private)
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 ⇒ self
(private)
#private(symbol, ...) ⇒ self
#private(string, ...) ⇒ self
self
(private)
#private(symbol, ...) ⇒ self
#private(string, ...) ⇒ self
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.
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:
.
# File 'vm_method.c', line 1731
static VALUE rb_mod_private(int argc, VALUE *argv, VALUE module) { return set_visibility(argc, argv, module, METHOD_VISI_PRIVATE); }
#private_class_method(symbol, ...) ⇒ mod
#private_class_method(string, ...) ⇒ mod
mod
#private_class_method(string, ...) ⇒ mod
# File 'vm_method.c', line 1773
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, ...) ⇒ mod
Makes a list of existing constants private.
# File 'variable.c', line 2819
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]
# File 'class.c', line 1278
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) ⇒ Boolean
#private_method_defined?(string) ⇒ Boolean
Boolean
#private_method_defined?(string) ⇒ Boolean
Returns true
if the named private method is defined by _ mod_ (or its included modules and, if mod is a class, its 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.method_defined? "method2" #=> false
# File 'vm_method.c', line 1398
static VALUE rb_mod_private_method_defined(VALUE mod, VALUE mid) { return check_definition(mod, mid, METHOD_VISI_PRIVATE); }
#protected ⇒ self
(private)
#protected(symbol, ...) ⇒ self
#protected(string, ...) ⇒ self
self
(private)
#protected(symbol, ...) ⇒ self
#protected(string, ...) ⇒ self
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.
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.
# File 'vm_method.c', line 1702
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.
# File 'class.c', line 1255
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) ⇒ Boolean
#protected_method_defined?(string) ⇒ Boolean
Boolean
#protected_method_defined?(string) ⇒ Boolean
Returns true
if the named protected method is defined by mod (or its included modules and, if mod is a class, its 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.method_defined? "method2" #=> true
# File 'vm_method.c', line 1432
static VALUE rb_mod_protected_method_defined(VALUE mod, VALUE mid) { return check_definition(mod, mid, METHOD_VISI_PROTECTED); }
#public ⇒ self
(private)
#public(symbol, ...) ⇒ self
#public(string, ...) ⇒ self
self
(private)
#public(symbol, ...) ⇒ self
#public(string, ...) ⇒ self
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.
# File 'vm_method.c', line 1675
static VALUE rb_mod_public(int argc, VALUE *argv, VALUE module) { return set_visibility(argc, argv, module, METHOD_VISI_PUBLIC); }
#public_class_method(symbol, ...) ⇒ mod
#public_class_method(string, ...) ⇒ mod
mod
#public_class_method(string, ...) ⇒ mod
Makes a list of existing class methods public.
::String arguments are converted to symbols.
# File 'vm_method.c', line 1747
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, ...) ⇒ mod
Makes a list of existing constants public.
# File 'variable.c', line 2833
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) ⇒ unbound_method
Similar to instance_method, searches public method only.
# File 'proc.c', line 1844
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(mod, Qundef, 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.
# File 'class.c', line 1293
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) ⇒ Boolean
#public_method_defined?(string) ⇒ Boolean
Boolean
#public_method_defined?(string) ⇒ Boolean
Returns true
if the named public method is defined by mod (or its included modules and, if mod is a class, its 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? "method2" #=> false
C.method_defined? "method2" #=> true
# File 'vm_method.c', line 1364
static VALUE rb_mod_public_method_defined(VALUE mod, VALUE mid) { return check_definition(mod, mid, METHOD_VISI_PUBLIC); }
#refine(mod) ⇒ Module
(private)
Refine mod in the receiver.
Returns a module, where refined methods are defined.
# File 'eval.c', line 1437
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_module_new(); RCLASS_SET_SUPER(refinement, superclass); 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; }
#remove_class_variable(sym) ⇒ Object
Removes the definition of the sym, returning that constant's value.
class Dummy
@@var = 99
puts @@var
remove_class_variable(:@@var)
p(defined? @@var)
end
produces:
99
nil
# File 'variable.c', line 3113
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, n = id; if (!id) { not_defined: rb_name_err_raise("class variable %1$s not defined for %2$s", mod, name); } rb_check_frozen(mod); if (RCLASS_IV_TBL(mod) && st_delete(RCLASS_IV_TBL(mod), &n, &val)) { return (VALUE)val; } if (rb_cvar_defined(mod, id)) { rb_name_err_raise("cannot remove %1$s for %2$s", mod, ID2SYM(id)); } goto not_defined; }
#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.
# File 'variable.c', line 2355
VALUE rb_mod_remove_const(VALUE mod, VALUE name) { const ID id = id_for_var(mod, name, a, constant); if (!id) { rb_name_err_raise("constant %2$s::%1$s not defined", mod, name); } return rb_const_remove(mod, id); }
#remove_method(symbol) ⇒ self
#remove_method(string) ⇒ self
self
#remove_method(string) ⇒ self
Removes the method identified by symbol from the current class. For an example, see #undef_method. ::String arguments are converted to symbols.
# File 'vm_method.c', line 1032
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; }
#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.
# File 'object.c', line 1739
static 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 = rb_ivar_get(klass, id__attached__); 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_str_dup(rb_class_name(klass)); }
#undef_method(symbol) ⇒ self
#undef_method(string) ⇒ self
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)
# File 'vm_method.c', line 1263
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; }
#using(module) ⇒ self
(private)
Import class refinements from module into the current class or module definition.
# File 'eval.c', line 1504
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; }