Module | Kernel

In:

lib/facets/more/lazy.rb
lib/facets/more/timer.rb
lib/facets/more/methodfilter.rb
lib/facets/more/eventhook.rb
lib/facets/more/behavior.rb
lib/facets/more/basicobject.rb
lib/facets/more/json.rb
lib/facets/more/nackclass.rb
lib/facets/more/reference.rb
lib/facets/more/bitmask.rb
lib/facets/more/cut.rb
lib/facets/more/nullclass.rb
lib/facets/more/association.rb
lib/facets/more/autoscript.rb
lib/facets/core/kernel/eigenclass.rb
lib/facets/core/kernel/called.rb
lib/facets/core/kernel/object_hexid.rb
lib/facets/core/kernel/set_with.rb
lib/facets/core/kernel/instvar.rb
lib/facets/core/kernel/constant.rb
lib/facets/core/kernel/__DIR__.rb
lib/facets/core/kernel/uri.rb
lib/facets/core/kernel/call_stack.rb
lib/facets/core/kernel/this.rb
lib/facets/core/kernel/p.rb
lib/facets/core/kernel/require_all.rb
lib/facets/core/kernel/warn_with_line.rb
lib/facets/core/kernel/instance_exec.rb
lib/facets/core/kernel/nack.rb
lib/facets/core/kernel/method.rb
lib/facets/core/kernel/demo.rb
lib/facets/core/kernel/get_by_id.rb
lib/facets/core/kernel/object_clone.rb
lib/facets/core/kernel/meta.rb
lib/facets/core/kernel/object_class.rb
lib/facets/core/kernel/resc.rb
lib/facets/core/kernel/supermethod.rb
lib/facets/core/kernel/__class__.rb
lib/facets/core/kernel/singleton.rb
lib/facets/core/kernel/ask.rb
lib/facets/core/kernel/as.rb
lib/facets/core/kernel/require_esc.rb
lib/facets/core/kernel/op_esc.rb
lib/facets/core/kernel/complete.rb
lib/facets/core/kernel/to_data.rb
lib/facets/core/kernel/is.rb
lib/facets/core/kernel/assign_with.rb
lib/facets/core/kernel/send_as.rb
lib/facets/core/kernel/set_from.rb
lib/facets/core/kernel/__self__.rb
lib/facets/core/kernel/singleton_class.rb
lib/facets/core/kernel/bool.rb
lib/facets/core/kernel/deep_clone.rb
lib/facets/core/kernel/silently.rb
lib/facets/core/kernel/methods.rb
lib/facets/core/kernel/cache.rb
lib/facets/core/kernel/fn.rb
lib/facets/core/kernel/in.rb
lib/facets/core/kernel/instance_assign.rb
lib/facets/core/kernel/with.rb
lib/facets/core/kernel/supress.rb
lib/facets/core/kernel/bug.rb
lib/facets/core/kernel/here.rb
lib/facets/core/kernel/callee.rb
lib/facets/core/kernel/require_local.rb
lib/facets/core/kernel/new.rb
lib/facets/core/kernel/pp_exception.rb
lib/facets/core/kernel/maybe.rb
lib/facets/core/kernel/autoreload.rb
lib/facets/core/kernel/assign_from.rb
lib/facets/core/kernel/deep_copy.rb
lib/facets/core/kernel/respond.rb
lib/facets/core/kernel/copy.rb
lib/facets/core/kernel/load_local.rb
lib/facets/core/kernel/populate.rb
lib/facets/core/kernel/meta_alias.rb
lib/facets/core/kernel/meta_def.rb
lib/facets/core/kernel/meta_eval.rb
lib/facets/core/kernel/class_def.rb
lib/facets/core/kernel/tap.rb
lib/facets/core/kernel/instance_class.rb
lib/facets/core/kernel/instance_values.rb
lib/facets/core/kernel/silence_stream.rb
lib/facets/core/kernel/enable_warnings.rb
lib/facets/core/kernel/daemonize.rb
lib/facets/core/kernel/object_send.rb
lib/facets/core/kernel/qua_class.rb
lib/facets/yore/annotation.rb
lib/facets/yore/kernel/require_facet.rb
lib/facets/yore/kernel/own.rb

Any object can be annotated.

### Methods

>> __DIR__ __self__ __singleton_class__ ann as ask assign_from assign_with associations autoreload autoreload_files autoreload_glob autoscript behaving bitmask bool? bug! cache call_stack class_def complete constant copy cut daemonize deep_clone deep_copy demand demo eigenclass enable_warnings event false? from_data future get_by_id hook in? instance_assign instance_class instance_exec instance_values instvar instvar! j jj maybe meta meta_alias meta_def meta_eval method! methods nack nack new null object_hexid object_send op_esc own p populate pp_exception promise qua_class ref resc respond returning send_as send_as set_from set_with silence_stream silence_warnings silently singleton singleton_class super_method supermethod suppress tap target timed to_data true? unuri uri warn_with_line with

### Classes and Modules

Class Kernel::As

### Constants

ASSOCIATIONS | = | Hash.new{ |h,k,v| h[k]=[] }
OPERATORS | = | %w{ +@ -@ + - ** * / % ~ <=> << >> < > === == =~ <= >= | & ^ []= [] }
OPERATORS_REGEXP | = | Regexp.new( '(' << OPERATORS.collect{ |k| Regexp.escape(k) }.join('|') << ')' )

OPERATORS_ESC_TABLE

=

{ "+@" => "op_plus_self", "-@" => "op_minus_self", "+" => "op_plus", "-" => "op_minus", "**" => "op_pow", "*" => "op_mul", "/" => "op_div", "%" => "op_mod", "~" => "op_tilde", "<=>" => "op_cmp", "<<" => "op_lshift", ">>" => "op_rshift", "<" => "op_lt", ">" => "op_gt", "===" => "op_case_eq", "==" => "op_equal", "=~" => "op_apply", "<=" => "op_lt_eq", ">=" => "op_gt_eq", "|" => "op_or", "&" => "op_and", "^" => "op_xor", "[]=" => "op_store", "[]" => "op_fetch"

### External Aliases

caller | -> | pp_call_stack

Parse a caller string and break it into its components, returning an array. Returns:

- file (String)
- lineno (Integer)
- method (Symbol)

For example, from irb,

      call_stack(1)

produces

[["(irb)", 2, :irb_binding],

     ["/usr/lib/ruby/1.8/irb/workspace.rb", 52, :irb_binding],
     ["/usr/lib/ruby/1.8/irb/workspace.rb", 52, nil]]

Note: If the user decides to redefine caller() to output data in a different format, prior to requiring this, then the results will be indeterminate.

dup | -> | object_dup
clone | -> | object_clone
class | -> | object_class
| Defines object_classas an alias of class. This is an alternative to class, akin to object_id.
class | -> | __class__
| Defines core method class as an alias of class. This allows you to use class as your own method, without loosing the ability to determine the object‘s class.
is_a? | -> | is?
| May deprecate so as not to confuse with module method.
lambda | -> | fn

A nice shorthand for lambda.

      adder = fn { |x,y| x + y }
      adder[1,2]  #=> 3

binding | -> | here

A shorthand pronoun for binding().

      a = 3
      b = here
      eval( "a", b )  #=> 3

### Public Instance methods

>>(to)

Define an association with `self`.

__DIR__()

Similar to FILE and LINE, DIR provides the directory path to the current executing script.

__self__()

Returns a Functor that allows one to call any Kernel or Object method bound to self, making it possible to bypass overrides of Kernel and Object methods.

      class A
        def object_id ; "OBTUSE" ; end
      end

      c = C.new
      c.object_id             #=> "OBTUSE"
      c.__self__.object_id    #=> 6664875832

__singleton_class__()

Alias for singleton_class

ann( *args )
as( ancestor, &blk )

Returns a As-functor that allows one to call any ancestor‘s method directly of the given object.

      class A
        def x ; 1 ; end
      end

      class B < A
        def x ; 2 ; end
      end

      class C < B
        def x ; as(A).x ; end
      end

      C.new.x  #=> 1

ask( question, answers=nil )

Convenience method to get simple console reply.

assign_from(obj, *fields)

Set instance vars using another object.

      class O
        attr_accessor :d
        def initialize( a, b, c, d)
          @a = a
          @b = b
          @c = c
          @d = d
        end
      end
      o1 = O.new(1,2,3,4)
      o2 = O.new(0,0,0,0)

      o2.assign_from( o1, '@a', '@b', '@c', '@d' )
      o2.instance_eval{ @a }  #=> 1
      o2.instance_eval{ @b }  #=> 2
      o2.instance_eval{ @c }  #=> 3
      o2.instance_eval{ @d }  #=> 4

See also assign_with.

assign_with(*args)

Set setter methods and/or vars using a hash (or assoc array). assign_with is a meta-programming method, which allows you to use a hash to do any kind of variable assignment and/or setting:

For example, assuming that there is an accessor defined as `d`:

      assign_with( '@a'=>1, '@@b'=>2, '$c'=>3, 'd'=>4 )
      @a   #=> 1
      @@b  #=> 2
      $c   #=> 3
      d    #=> 4

Note that while the global variable is strictly unnecessary, it works for completeness sake.

associations()
autoreload( *args )

Autoreload feature files.

Automatically reload, at regular intervals, any previously loaded features, and/or other files not already loaded, if they have been modified since the last interval check. A numeric parameter sets the reload interval in seconds and the file parameter can either be a glob string or an array of file paths. If a glob string, it is expanded only once on the initial method call. Supplying a boolean parameter of ‘false’ will force autreload to skip previously loaded features and only reload the specified files. Also keeps a "dirty" flag.

autoreload_files( *args )

Same as autoreload, but does not include previously loaded features. This is equivalent to as adding a ‘false’ parameter to autoreload.

autoreload_glob( *args )

Alias for autoreload_files

autoscript(mod, filename)

Calls Object.autoscript.

behaving(behavior, &body)
bitmask(bit)
bool?()

Returns true is an object is class TrueClass or FalseClass, otherwise false.

      true.bool?   #=> true
      false.bool?  #=> true
      nil.bool?    #=> false

bug!( message = 'must not happen' )

Raises a ScritBug error with a message.

      if find_bug then
        bug! "unknown bug found"
      end

cache(m = nil)

Object#cache is essentially like Module#memoize except it can also be used on singleton/eigen methods. OTOH, memoize‘s implementation is arguably better for it‘s use of bind instead of alias. Eventually the two implmenations will be reconciled with a single implmentation.

call_stack( level = 1 )
class_def(name, &blk)

Defines an instance method within a class.

complete() {|| ...}
constant(const)

This is similar to +Module#const_get+ but is accessible at all levels, and, unlike `const_get`, can handle module hierarchy.

      constant("Fixnum")                  # -> Fixnum
      constant(:Fixnum)                   # -> Fixnum

      constant("Process::Sys")            # -> Process::Sys
      constant("Regexp::MULTILINE")       # -> 4

      require 'test/unit'
      Test.constant("Unit::Assertions")   # -> Test::Unit::Assertions
      Test.constant("::Test::Unit")       # -> Test::Unit

copy()

Anything that can be marshaled can be copied in totality. This is also commonly called a deep_copy.

      "ABC".copy  #=> "ABC"

cut( cutclass, &block )
daemonize()

Turns the current script into a daemon process that detaches from the console. It can be shut down with a TERM signal.

deep_clone( obj=self, cloned={} )

Adds deep_clone method to an object which produces deep copy of it. It means if you clone a Hash, every nested items and their nested items will be cloned. Moreover deep_clone checks if the object is already cloned to prevent endless recursion.

      obj = []
      a = [ true, false, obj ]
      b = a.deep_clone
      obj.push( 'foo' )
      p obj   # >> [ 'foo' ]
      p b[2]  # >> []

deep_copy()

Anything that can be marshaled can be copied in totality. This is also just called copy.

      "ABC".deep_copy  #=> "ABC"

demand( promise )

Forces the result of a promise to be computed (if necessary) and returns the bare result object. Once evaluated, the result of the promise will be cached. Nested promises will be evaluated together, until the first non-promise result.

If called on a value that is not a promise, it will simply return it.

demo(out=$stdout,&block)

For debugging and showing examples. Currently this takes an argument of a string in a block.

      demo {%{ a = [1,2,3] }}
      demo {%{ a.slice(1,2) }}
      demo {%{ a.map { |x| x**3 } }}

Produces:

      a = [1,2,3]             #=>  [1, 2, 3]
      a.slice(1,2)            #=>  [2, 3]
      a.map { |x| x**3 }      #=>  [1, 8, 27]

eigenclass()
enable_warnings() {|| ...}

Sets $VERBOSE to true for the duration of the block and back to its original value afterwards.

event(sym) {|| ...}
false?()

Returns true is an object is class FalseClass, otherwise false.

      true.false?   #=> false
      false.false?  #=> true
      nil.false?    #=> false

from_data(snap)

Restore objects state from a hash representation of the object.

future( ) {|result| ...}

Schedules a computation to be run asynchronously in a background thread and returns a promise for its result. An attempt to demand the result of the promise will block until the computation finishes.

As with Kernel.promise, this passes the block a promise for its own result. Use wisely.

get_by_id( id )
hook(sym)
in?(other)

Is self included in other?

      5.in?(0..10)       #=> true
      5.in?([0,1,2,3])   #=> false

instance_assign( name, value )

Universal assignment. This is a meta-programming method, which allows you to assign any type of variable.

instance_class( &block )

Easy access to an object qua class, otherwise known as the object‘s metaclass or singleton class. This implemnetation alwasy returns the class, even if a block is provided to eval against it.

        It is what it is.

                  -- transonoma

instance_exec(*arguments, &block)
instance_values()
instvar( sym )
instvar!( sym, val )
j(*objs)

Outputs objs to STDOUT as JSON strings in the shortest form, that is in one line.

jj(*objs)

Ouputs objs to STDOUT as JSON strings in a pretty format, with indentation and over many lines.

maybe(chance = 0.5) {|if rand < chance| ...}

Random generator that returns true or false. Can also take a block that has a 50/50 chance to being executed.

      maybe  #=> true
      maybe  #=> false

meta()

Provides access to an object‘s metaclass (ie. singleton) by-passsing access provisions. So for example:

      class X
        meta.attr_accesser :a
      end

      X.a = 1
      X.a #=> 1

meta_alias(*args)

Alias a method defined in the metaclass (ie. singleton class).

meta_def( name, &block )

Add method to a meta-class.

meta_eval( str=nil, &blk )

Evaluate code in a metaclass.

method!(s)

Easy access to method as objects, and they retain state!

      def hello
        puts "Hello World!"
      end
      p method!(:hello)   #=> <Method: #hello>

methods(*args)

Returns a list of methods according to symbol(s) given.

Usable symbols include:

- `:inherited` or `:ancestors`
- `:local` or `:no_ancestors`
- `:public`
- `:private`
- `:protected`
- `:singleton`
- `:all`

It no symbol is given then :public is assumed. Unrecognized symbols raise an error.

      def test
        puts("Hello World!")
      end

      methods(:local)    #=> ['test']

nack(err=nil, *data, &ctrl)
nack()
new()

Synonymous with clone, this is an interesting method in that it promotes prototype-based Ruby. Now Classes aren‘t the only things that respond to new.

      "ABC".new  => "ABC"

null()
object_hexid()

Returns the object id as a string in hexideciaml, which is how Ruby reports them with inspect.

      "ABC".object_hexid  #=> "0x402d359c"

object_send(name,*args,&blk)

Send only to public methods.

op_esc( str )
own(&blk)

Easy access to an object‘s specialized class, otherwise known as it‘s metaclass or singleton class.

p( x )

alias_method :pr, :p

     REdefines standrard #p kernel method
     to pass through its argument.

populate( data=nil, &yld )

Similiar to set_with, but ignores missing setters.

pp_exception(ex)

Pretty prints an exception/error object usefull for helpfull debug messages

Input: The Exception/StandardError object

Output: the pretty printed string

promise( ) {|result| ...}

The promise() function is used together with demand() to implement lazy evaluation. It returns a promise to evaluate the provided block at a future time. Evaluation can be demanded and the block‘s result obtained via the demand() function.

Implicit evaluation is also supported: the first message sent to it will demand evaluation, after which that message and any subsequent messages will be forwarded to the result object.

As an aid to circular programming, the block will be passed a promise for its own result when it is evaluated. Be careful not to force that promise during the computation, lest the computation diverge.

qua_class(&block)

Easy access to an object qua class, otherwise known as the object‘s metaclass or singleton class.

Yes, another one.

ref(x)

Shortcut reference constructor.

resc(x)

Provides a shortcut to the Regexp.escape module method.

respond(sym, *args)

Like respond_to? but returns the result of the call if it does respond.

(This is used to be called respond_with_value.)

returning(obj=self)

Alias for with

send_as( ancestor, sym, *args, &blk )

Call parent class/module methods once bound to self.

send_as( ancestor, sym, *args, &blk )

alias_method :as, :as

set_from(obj, *fields)

Set setter methods using a another object.

      class X
        attr_accessor :a, :b
        def initialize( a, b )
           @a,@b = a,b
        end
      end

      obj1 = X.new( 1, 2 )
      obj2 = X.new

      obj2.set_from(obj1)

      obj2.a  #=> 1
      obj2.b  #=> 2

set_with(*args) {|| ...}

Assign via setter methods using a hash, associative array or block.

      object.set_with( :a => 1, :b => 2 )
      object.set_with( :a, 1, :b, 2 )
      object.set_with( [:a, 1], [:b, 2] )
      object.set_with( *[[:a, 1], [:b, 2]] )
      object.set_with{ |s| s.a = 1; s.b = 2 }

These are all the same as doing:

      object.a = 1
      object.b = 2

The array forms gaurentees order of operation.

This method does not check to make sure the object repsonds to the setter method. For that see populate.

silence_stream(stream) {|| ...}

Silences any stream for the duration of the block.

      silence_stream(STDOUT) do
        puts 'This will never be seen'
      end

      puts 'But this will'

silence_warnings(

Alias for silently

silently( {|| ...}

Temporarily turn-off verbose mode while yielding block.

singleton()

Access to an object‘s "special" class, otherwise known as it‘s eigenclass or metaclass, etc.

One day these names must be reconciled!

singleton_class()

Access to an object‘s "special" class, otherwise known as it‘s eigenclass or metaclass or own, etc.

One day these names must be reconciled!

super_method(klass, meth)

Alias for supermethod

supermethod(klass, meth)

Returns method of a parent class bound to self.

suppress(*exception_classes) {|| ...}

Supress errors while executing a block, with execptions.

tap() {|self| ...}

Yield self and return self.

target( name, &superblock )
timed() {|timer = Timer.new.start| ...}

Takes a block and returns the total time it took to execute.

to_data( deep=false )

Create a hash representation of an object.

true?()

Returns true is an object is class TrueClass, otherwise false.

      true.true?   #=> true
      false.true?  #=> false
      nil.true?    #=> false

unuri( s )
uri( s, w=%r{[^a-zA-Z_0-9./-]} )
warn_with_line(msg="", fulltrace=nil)

Like warn produces the current line number as well.

      warn_with_line("You have been warned.")

produces

      3: Warning: You have been warned.

Note that this method depends on the output of caller.

with(obj=self) {|obj| ...}

A Ruby-ized realization of the K combinator.

      with Book.new do |book|
        book.title = "Imperium"
        book.author = "Ulick Varange"
      end

Also aliased as returning for readability.

      def foo
        returning values = [] do
          values << 'bar'
          values << 'baz'
        end
      end

      foo # => ['bar', 'baz']

[Validate]