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"
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 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]
A representation of a C function
@libc = Fiddle.dlopen "/lib/libc.so.6" #=> #<Fiddle::Handle:0x00000001d7a8d8> f = Fiddle::Function.new( @libc['strcpy'], [Fiddle::TYPE_VOIDP, Fiddle::TYPE_VOIDP], Fiddle::TYPE_VOIDP) #=> #<Fiddle::Function:0x00000001d8ee00> buff = "000" #=> "000" str = f.call(buff, "123") #=> #<Fiddle::Pointer:0x00000001d0c380 ptr=0x000000018a21b8 size=0 free=0x00000000000000> str.to_s => "123"
@libc = Fiddle.dlopen "/lib/libc.so.6" #=> #<Fiddle::Handle:0x00000001d7a8d8> f = Fiddle::Function.new(@libc['strcpy'], [TYPE_VOIDP, TYPE_VOIDP], TYPE_VOIDP) #=> #<Fiddle::Function:0x00000001d8ee00> f.abi == Fiddle::Function::DEFAULT #=> true
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!
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
Create unnamed module, define methodname as instance method of it, and return it.
example:
filename = 'example.rhtml' # 'arg1' and 'arg2' are used in example.rhtml erb = ERB.new(File.read(filename)) erb.filename = filename MyModule = erb.def_module('render(arg1, arg2)') class MyClass include MyModule end
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]
Invokes Module.append_features
on each parameter in reverse order.
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"
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
.
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"
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
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]
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?
.
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.
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.
Returns a new Fiddle::Function
instance at the memory address of the given name
function.
Raises a DLError
if the name
doesn’t exist.
argtype
is an Array
of arguments, passed to the name
function.
ctype
is the return type of the function
call_type
is the ABI of the function
See also Fiddle:Function.new
See Fiddle::CompositeHandler.sym
and Fiddle::Handler.sym
Returns a new closure wrapper for the name
function.
ctype
is the return type of the function
argtype
is an Array
of arguments, passed to the callback function
call_type
is the abi of the closure
block
is passed to the callback
See Fiddle::Closure
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
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]
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.
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
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!
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)
Calls the constructed Function
, with args
. Caller must ensure the underlying function is called in a thread-safe manner if running in a multi-threaded process.
Note that it is not thread-safe to use this method to directly or indirectly call many Ruby C-extension APIs unless you don’t pass +need_gvl: true+ to Fiddle::Function#new.
For an example see Fiddle::Function