module Kernel

Public Instance Methods

Bit(n) click to toggle source

Create a single bit bitmask.

Bit(0)  #=> 1
Bit(1)  #=> 2
Bit(2)  #=> 4

This is equivalent to n-shift: “1 << n”.

CREDIT: Thomas Sawyer, George Moschovitis

# File lib/core/facets/bitmask.rb, line 97
def Bit(n)
  1 << Integer(n)
end
__DIR__() click to toggle source

Similar to __FILE__, __DIR__ provides the directory path to the current executing script.

CREDIT: Trans

# File lib/core/facets/kernel/__dir__.rb, line 8
def __DIR__
  c = caller.first
  return nil unless c.rindex(/:\d+(:in `.*')?$/)
  file = $` # File.dirname(c)
  return nil if /\A\((.*)\)/ =~ file # eval, etc.
  #File.expand_path(File.dirname(file))
  File.dirname(file)
end
__HERE__() click to toggle source

Outputs the file, line and current method.

caller(1).first
"/usr/lib/ruby/1.8/irb/workspace.rb:52:in `irb_binding'"

CREDIT: William Mason

# File lib/core/facets/kernel/__here__.rb, line 9
def __HERE__
  caller(1).first
end
__callee__() click to toggle source

Retreive the current running method name.

def tester; __callee__; end
tester  #=> :tester

Technically __callee__ should provided alias names, where as __method__ should not. But we'll have to leave that distinction to Ruby 1.9+.

# File lib/core/facets/kernel/__method__.rb, line 33
def __callee__
  /\`([^\]+)\/.match(caller(1).first)[1].to_sym
end
__method__() click to toggle source

Retreive the current running method name.

def tester; __method__; end
tester  #=> :tester

Technically __callee__ should provided alias names, where __method__ should not. But we'll have to leave that distinction to Ruby 1.9+.

# File lib/core/facets/kernel/__method__.rb, line 14
def __method__
  /\`([^\]+)\/.match(caller(1).first)[1].to_sym
end
_extend(*mod, &blk)
Alias for: extend
as(ancestor, &blk) click to toggle source

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
# File lib/core/facets/kernel/as.rb, line 22
def as(ancestor, &blk)
  @__as ||= {}
  unless r = @__as[ancestor]
    r = (@__as[ancestor] = As.new(self, ancestor))
  end
  r.instance_eval(&blk) if block_given?
  #yield(r) if block_given?
  r
end
ask(question, answers=nil) click to toggle source

Very simple convenience method to get a console reply.

ask "Are you happy?", "Yn"

On the command line one would see.

$ Are you happy? [Yn]

Responding:

$ Are you happy? [Yn] Y <ENTER>

The ask method would return “Y”.

# File lib/core/facets/kernel/ask.rb, line 19
def ask(question, answers=nil)
  $stdout << "#{question}"
  $stdout << " [#{answers}] " if answers
  $stdout.flush
  until inp = $stdin.gets ; sleep 1 ; end
  inp.strip
end
attr_singleton_accessor(*args) click to toggle source

Takes an array or hash with default values and creates singleton attr_accessors for each.

attr_singleton_accessor { :x => 1, :y => 2 }
@x          #=> 1
@y          #=> 2
self.x = 3
self.y = 4
self.x      #=> 3
self.y      #=> 4

CREDIT: Trans

# File lib/core/facets/kernel/attr_singleton.rb, line 54
def attr_singleton_accessor(*args)
  #h, a = *args.partition{|a| Hash===a}
  (class << self ; self ; end).send( :attr_accessor, *args )
  #(class << self ; self ; end).send( :attr_accessor, *h.keys )
  #h.each { |k,v| instance_variable_set("@#{k}", v) }
end
attr_singleton_reader(*args) click to toggle source

Takes an array or a hash with default values and creates singleton attr_readers for each.

attr_singleton_reader {:x => 1, :y => 2}
@x       #=> 1
@y       #=> 2
self.x   #=> 1
self.y   #=> 2

CREDIT: Trans

# File lib/core/facets/kernel/attr_singleton.rb, line 14
def attr_singleton_reader(*args)
  #h, a = *args.partition{|a| Hash===a}
  (class << self ; self ; end).send( :attr_reader, *args )
  #(class << self ; self ; end).send( :attr_reader, *h.keys )
  #h.each { |k,v| instance_variable_set("@#{k}", v) }
end
attr_singleton_writer(*args) click to toggle source

Takes an array or a hash with default values and creates singleton attr_writers for each.

attr_singleton_writer { :x => 1, :y => 2 }
@x           #=> 1
@y           #=> 2
self.x = 3
self.y = 4
@x           #=> 3
@y           #=> 4

CREDIT: Trans

# File lib/core/facets/kernel/attr_singleton.rb, line 34
def attr_singleton_writer(*args)
  #h, a = *args.partition{|a| Hash===a}
  (class << self ; self ; end).send( :attr_writer, *args )
  #(class << self ; self ; end).send( :attr_writer, *h.keys )
  #h.each { |k,v| instance_variable_set("@#{k}", v) }
end
autoreload( *args ) click to toggle source

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.

# File lib/more/facets/autoreload.rb, line 50
def autoreload( *args )

  check_interval=10
  include_features = true
  files = nil

  args.each do |arg|
    case arg
    when Numeric
      check_interval = arg
    when String
      files = Dir.glob( arg )
    when Array
      files = arg
    when TrueClass, FalseClass
      include_features = arg
    end
  end

  file_mtime = {}

  Thread.new(Time.now) do |start_time|
    loop do
      sleep check_interval

      if include_features
        feature_files = $LOADED_FEATURES.collect { |feature|
          $LOAD_PATH.each { |lp| file = File.join(lp, feature) }
        }.flatten

        feature_files.each { |file|
          if File.exists?(file) and (mtime = File.stat(file).mtime) > (file_mtime[file] || start_time)
            $autoreload_dirty = true
            file_mtime[file] = mtime
            STDERR.puts "File '#{ file }' reloaded"
            begin
              load(file)
            rescue Exception => e
              STDERR.puts e.inspect
            end
          end
        }
      end

      if files
        files.each do |file|
          if File.exists?(file) and (mtime = File.stat(file).mtime) > (file_mtime[file] || start_time)
            $autoreload_dirty = true
            file_mtime[file] = mtime
            STDERR.puts "File '#{ file }' changed"
          end
        end
      end

    end
  end

end
autoreload_files( *args ) click to toggle source

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

# File lib/more/facets/autoreload.rb, line 112
def autoreload_files( *args )
  autoreload( false, *args )
end
blank?() click to toggle source

An object is blank if it's nil, empty, or a whitespace string. For example, “”, “ ”, nil, [], and {} are blank.

This simplifies

if !address.nil? && !address.empty?

to

if !address.blank?
# File lib/core/facets/blank.rb, line 14
def blank?
  respond_to?(:empty?) ? empty? : !self
end
bool?() click to toggle source

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

true.bool?   #=> true
false.bool?  #=> true
nil.bool?    #=> false
# File lib/core/facets/boolean.rb, line 127
def bool?
  (true == self or false == self)
end
callstack( level = 1 ) click to toggle source

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.

CREDIT: Trans

# File lib/core/facets/kernel/callstack.rb, line 27
def callstack( level = 1 )
  call_str_array = pp_callstack(level)
  stack = []
  call_str_array.each{ |call_str|
    file, lineno, method = call_str.split(':')
    if method =~ /in `(.*)'/ then
      method = $1.intern()
    end
    stack << [file, lineno.to_i, method]
  }
  stack
end
complete() { || ... } click to toggle source

Repeat loop until it yeilds false or nil.

a = [3, 2, 1]
complete do
  b << a.pop
end
b  #=> [3, 2, 1, nil]

CREDIT: Trans

# File lib/core/facets/kernel/complete.rb, line 13
def complete
  loop { break unless yield }
end
constant(const) click to toggle source

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

CREDIT: Trans

# File lib/core/facets/kernel/constant.rb, line 18
def constant(const)
  const = const.to_s.dup
  base = const.sub!(/^::/, '') ? Object : ( self.kind_of?(Module) ? self : self.class )
  const.split(/::/).inject(base){ |mod, name| mod.const_get(name) }
end
d(*x) click to toggle source

Like p but gives file and line number.

d("hi")

produces

"hi" (/home/dave/projects/foo.rb, 38)
# File lib/core/facets/kernel/d.rb, line 11
def d(*x)
  puts "#{x.inspect} #{caller[0]}"
  return *x
end
daemonize() click to toggle source

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

# File lib/more/facets/daemonize.rb, line 31
def daemonize
  exit if fork                   # Parent exits, child continues.
  Process.setsid                 # Become session leader.
  exit if fork                   # Zap session leader. See [1].
  Dir.chdir "/"                  # Release old working directory.
  File.umask 0000                # Ensure sensible umask. Adjust as needed.
  STDIN.reopen "/dev/null"       # Free file descriptors and
  STDOUT.reopen "/dev/null", "a" # point them somewhere sensible.
  STDERR.reopen STDOUT           # STDOUT/ERR should better go to a logfile.
  trap("TERM") { exit }
end
deep_copy() click to toggle source

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

"ABC".copy  #=> "ABC"
# File lib/core/facets/kernel/deep_copy.rb, line 8
def deep_copy
  Marshal::load(Marshal::dump(self))
end
demand( promise ) click to toggle source

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.

# File lib/core/facets/lazy.rb, line 219
def demand( promise )
  if promise.respond_to? :__result__
    promise.__result__
  else # not really a promise
    promise
  end
end
demo(out=$stdout,&block) click to toggle source

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

demo {%Q{ a = [1,2,3] }}
demo {%Q{ a.slice(1,2) }}
demo {%Q{ 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]

TODO: Is there a way to do this without the eval string in block? Preferably just a block and no string.

# File lib/core/facets/kernel/demo.rb, line 19
def demo(out=$stdout,&block)
  out << sprintf("%-25s#=>  %s\n", expr = block.call, eval(expr, block.binding).inspect)
end
enable_warnings() { || ... } click to toggle source

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

CREDIT: David Heinemeier Hansson

# File lib/core/facets/kernel/silence.rb, line 67
def enable_warnings
  old_verbose, $VERBOSE = $VERBOSE, true
  yield
ensure
  $VERBOSE = old_verbose
end
equate?(x) click to toggle source

Broad equality.

Checks to see if the object x is in any way equal to the reciever, starting with the identity equals? and ending with ===.

# File lib/core/facets/kernel/equate.rb, line 9
def equate?(x)
  equal?(x) || eql?(x) || self == x || self === x
end
ergo() { |self| ... } click to toggle source

Yield self -or- return self.

"a".ergo.upcase #=> "A"
nil.ergo.foobar #=> nil

"a".ergo{ |o| o.upcase } #=> "A"
nil.ergo{ |o| o.foobar } #=> nil

This is like tap, but tap yields self -and- returns self.

CREDIT: Daniel DeLorme

# File lib/core/facets/kernel/ergo.rb, line 17
def ergo &b
  if block_given?
    b.arity == 1 ? yield(self) : instance_eval(&b)
  else
    self
  end
end
extend(*mod, &blk) click to toggle source
# File lib/core/facets/kernel/extend.rb, line 5
def extend(*mod, &blk)
  _extend *mod unless mod.empty?
  _extend Module.new(&blk) if blk
end
Also aliased as: _extend
extension() click to toggle source

Don't say it!

# File lib/core/facets/kernel/extension.rb, line 4
def extension
  class << self; self; end
end
false?() click to toggle source

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

true.false?   #=> false
false.false?  #=> true
nil.false?    #=> false
# File lib/core/facets/boolean.rb, line 116
def false?
  (false == self)
end
future( ) { |result| ... } click to toggle source

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 #promise, this passes the block a promise for its own result. Use wisely.

# File lib/core/facets/lazy.rb, line 234
def future( &computation ) #:yields: result
  Lazy::Future.new(&computation)
end
in?(other) click to toggle source

Is self included in other?

5.in?(0..10)       #=> true
5.in?([0,1,2,3])   #=> false
# File lib/core/facets/kernel/in.rb, line 8
def in?(other)
  other.include?(self)
end
instance_assign(hash) click to toggle source

Set instance variables using a hash.

instance_assign('@a'=>1, '@b'=>2)
@a   #=> 1
@b   #=> 2

WARNING: instance_assign will be deprecated. Use instance_vars.update instead.

# File lib/core/facets/kernel/instance_assign.rb, line 32
def instance_assign(hash)
  hash.each do |k,v|
    k = "@#{k}" if k !~ /^@/
    instance_variable_set(k, v)
  end
  return self
end
instance_class(&block) click to toggle source

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.
But I think I like this one best.

CREDIT: Trans

# File lib/core/facets/kernel/instance_class.rb, line 20
def instance_class(&block)
  (class << self; self; end).module_eval(&block) if block
  (class << self; self; end)
end
instance_values() click to toggle source

Return instance variable values in an array.

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

x = X.new(1,2)

x.instance_values   #=> { "a"=>1, "b"=>2 }

WARNING: instance_values will be deprecated. Use instance_vars.to_hash instead.

# File lib/core/facets/kernel/instance_assign.rb, line 17
def instance_values
  instance_variables.inject({}) do |values, name|
    values[name[1..-1]] = instance_variable_get(name)
    values
  end
end
instance_vars() click to toggle source
# File lib/core/facets/kernel/instance_variables.rb, line 3
def instance_vars
  InstanceVariables.new(self)
end
load_local(relative_feature, safe=nil)

Backward compatability.

Alias for: load_relative
load_relative(relative_feature, safe=nil) click to toggle source

Load file from same dir as calling script.

load_local 'templib'

CREDIT: Paul Brannan, Pragmatic Programmers

# File lib/core/facets/kernel/require_relative.rb, line 35
def load_relative(relative_feature, safe=nil)
  c = caller.first
  fail "Can't parse #{c}" unless c.rindex(/:\d+(:in `.*')?$/)
  file = $` # File.dirname(c)
  if /\A\((.*)\)/ =~ file # eval, etc.
    raise LoadError, "require_relative is called in #{$1}"
  end
  absolute = File.expand_path(relative_feature, File.dirname(file))
  load absolute, safe
end
Also aliased as: load_local
maybe(chance = 0.5) { || ... } click to toggle source

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
# File lib/core/facets/kernel/maybe.rb, line 9
def maybe(chance = 0.5, &block)
  if block then
    yield if rand < chance
  else
    rand < chance
  end
end
meta_alias(*args) click to toggle source

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

def X.y?; "y?" ; end
X.meta_alias "ynot?", "y?"
X.ynot?  #=> y?

CREDIT: Trans

# File lib/core/facets/kernel/meta_alias.rb, line 11
def meta_alias(*args)
  meta_class do
    alias_method(*args)
  end
end
meta_class(&block) click to toggle source

Easy access to an object's “special” class, otherwise known as it's metaclass or singleton class.

# File lib/core/facets/kernel/meta_class.rb, line 6
def meta_class(&block)
  if block_given?
    (class << self; self; end).class_eval(&block)
  else
    (class << self; self; end)
  end
end
Also aliased as: metaclass
meta_def( name, &block ) click to toggle source

Add method to a meta-class –i.e. a singleton method.

class X; end
X.meta_def(:x){"x"}
X.x  #=> "x"

CREDIT: WhyTheLuckyStiff

# File lib/core/facets/kernel/meta_def.rb, line 11
def meta_def( name, &block )
  meta_class do
    define_method( name, &block )
  end
end
meta_eval(str=nil, &blk) click to toggle source

Evaluate code in a metaclass. This is equivalent to 'meta_class.instance_eval'.

CREDIT: WhyTheLuckyStiff

# File lib/core/facets/kernel/meta_eval.rb, line 9
def meta_eval(str=nil, &blk)
  if str
    meta_class.instance_eval(str)
  else
    meta_class.instance_eval(&blk)
  end
end
metaclass(&block)
Alias for: meta_class
method!(s) click to toggle source

Easy access to method as object, and they retain state.

def hello
  puts "Hello World!"
end

m1 = method!(:hello)   #=> <Method: #hello>

def m1.annotate
  "simple example"
end

m2 = method!(:hello)
m2.annotate  #=> "simple example"
# File lib/core/facets/kernel/method.rb, line 20
def method!(s)
  #( @__methods__ ||= {} )[s.to_sym] ||= method(s)
  $FIRST_CLASS_METHODS[self][s.to_sym] ||= method(s)
end
non_nil?()
Alias for: not_nil?
not_nil?() click to toggle source

The opposite of nil?.

"hello".not_nil?     # -> true
nil.not_nil?         # -> false

CREDIT: Gavin Sinclair

# File lib/core/facets/kernel/not_nil.rb, line 10
def not_nil?
  not nil?
end
Also aliased as: non_nil?
null() click to toggle source
# File lib/more/facets/nullclass.rb, line 51
def null
  NullClass.new
end
object_hexid() click to toggle source

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

"ABC".object_hexid  #=> "0x402d359c"
# File lib/core/facets/kernel/object_hexid.rb, line 10
def object_hexid
  return "0x" << (('%.x' % (2*self.__id__))[1..-1])
end
object_send(name,*args,&blk) click to toggle source

Send only to public methods.

class X
  private
  def foo; end
end

X.new.object_send(:foo)
=> NoMethodError: private method %xfoo' called for #<X:0xb7ac6ba8>

TODO: #object_send needs to change for 1.9.

CREDIT: Trans

# File lib/core/facets/kernel/object_send.rb, line 20
def object_send(name,*args,&blk)
  #instance_eval "self.#{name}(*args)"
  if respond_to?(name)
    __send__(name,*args,&blk)
  else #if respond_to?(:method_missing)
    __send__(:method_missing,name,*args,&blk)
  #else
  #  raise NoMethodError
  end
end
p(*x) click to toggle source

Alternate to standard p method that outputs Kernel#inspect to stdout, but also passes through the orginal argument(s).

x = 1
r = 4 + q(1)
p r

produces

1
5

TODO: DEPRECATE as of 1.9, if it will do this.

# File lib/core/facets/kernel/p.rb, line 18
def p(*x)
  x.each{ |e| puts e.inspect } #p(*x)
  x.size > 1 ? x : x.last #x.last
end
populate(data=nil) { || ... } click to toggle source

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

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

These are all the same as doing:

object.a = 1
object.b = 2

Using an associative array instead of hash guarentees order of assignemnt.

Using a hash or array will not raise an error if the accessor does not exits – it will simply be skipped.

(See also: instance_vars.update, which sets instance variables directly, bypassing accessor method.)

TODO: Better name, set_with ?

# File lib/core/facets/kernel/populate.rb, line 27
def populate(data=nil) #:yield:
  if data
    data.each do |k,v|
      send("#{k}=", v) if respond_to?("#{k}=")
    end
  end
  yield(self) if block_given?
  self
end
promise( ) { |result| ... } click to toggle source

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.

# File lib/core/facets/lazy.rb, line 208
def promise( &computation ) #:yields: result
  Lazy::Promise.new(&computation)
end
qua_class(&block) click to toggle source

Easy access to an object qua class, otherwise known as the object's singleton class.

Yes, another one.

CREDIT: Trans

# File lib/core/facets/kernel/qua_class.rb, line 10
def qua_class(&block)
  if block_given?
    (class << self; self; end).class_eval(&block)
  else
    (class << self; self; end)
  end
end
ref(x) click to toggle source

Shortcut reference constructor.

# File lib/more/facets/reference.rb, line 78
def ref(x)
  Reference.new(x)
end
require_all(pat) click to toggle source

Require a pattern of files. This make is easy to require an entire directory, for instance.

require_all 'facets/time/*'

You can also you require_all relative to the current script simply by using __DIR__.

require_all(__DIR__ + '/foo/*')
# File lib/core/facets/kernel/require_all.rb, line 13
def require_all(pat)
  $LOAD_PATH.each do |path|
    fs = Dir[File.join(path,pat)]
    unless fs.empty?
      fs.each { |f|
        Kernel.require(f) unless File.directory?(f)
      }
      break;
    end
  end
end
require_local(relative_feature)

Backward compatability.

Alias for: require_relative
require_relative(relative_feature) click to toggle source

Require file from same dir as calling script.

require_local 'templib'

CREDIT: Paul Brannan, Pragmatic Programmers

# File lib/core/facets/kernel/require_relative.rb, line 11
def require_relative(relative_feature)
  c = caller.first
  fail "Can't parse #{c}" unless c.rindex(/:\d+(:in `.*')?$/)
  file = $` # File.dirname(c)
  if /\A\((.*)\)/ =~ file # eval, etc.
    raise LoadError, "require_relative is called in #{$1}"
  end
  absolute = File.expand_path(relative_feature, File.dirname(file))
  require absolute
end
Also aliased as: require_local
resc(str) click to toggle source

Provides a shortcut to the Regexp.escape module method.

resc("H..LO")   #=> "H\\.\\.LO"

TODO: Should this be deprecated in favor of String#to_re/to_rx ?

CREDIT: Trans

# File lib/core/facets/kernel/resc.rb, line 11
def resc(str)
  Regexp.escape(str.to_s)
end
respond(sym, *args) click to toggle source

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

class X
  def f; "f"; end
end

x = X.new
x.respond(:f)  #=> "f"
x.respond(:g)  #=> nil

CREDIT: Trans

# File lib/core/facets/kernel/respond.rb, line 16
def respond(sym, *args)
  return nil if not respond_to?(sym)
  send(sym, *args)
end
Also aliased as: respond_with_value
respond_with_value(sym, *args)
Alias for: respond
returning(obj=self) { || ... } click to toggle source

A Ruby-ized realization of the K combinator.

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

Technically, returning probably should force the return of the stated object irregardless of any return statements that might appear within it's block. This might differentiate returning from with, however it also would require implementation in Ruby itself.

CREDIT: Mikael Brockman

# File lib/core/facets/kernel/returning.rb, line 18
def returning(obj=self) #:yield:
  yield obj
  obj
end
send_as(ancestor, sym, *args, &blk) click to toggle source

Call parent class/module methods once bound to self.

TODO: Does this have the proper scope for send?

# File lib/core/facets/kernel/as.rb, line 36
def send_as(ancestor, sym, *args, &blk)
  ancestor.instance_method(sym).bind(self).call(*args,&blk)
end
set_from(obj, *fields) click to toggle source

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

TODO: populate_from(obj) ?

# File lib/core/facets/kernel/populate.rb, line 56
def set_from(obj, *fields)
  unless fields.empty?
    fields.each do |k|
      send( "#{k}=", obj.send("#{k}") )  #if self.respond_to?("#{k}=") && obj.respond_to?("#{k}")
    end
  else
    setters = methods.collect { |m| m =~ /=$/ }
    setters.each do |setter|
      getter = setter.chomp('=')
      if obj.respond_to?(getter)
        send( setter, obj.send(getter) )
        fields < getter
      end
    end
  end
  fields
end
silence_stderr() { || ... } click to toggle source
# File lib/core/facets/kernel/silence.rb, line 27
def silence_stderr #:yeild:
  silence_stream(STDERR) { yield }
end
silence_stdout() { || ... } click to toggle source
# File lib/core/facets/kernel/silence.rb, line 32
def silence_stdout #:yeild:
  silence_stream(STDOUT) { yield }
end
silence_stream(*streams) { || ... } click to toggle source

Silences any stream for the duration of the block.

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

puts 'But this will'

CREDIT: David Heinemeier Hansson

# File lib/core/facets/kernel/silence.rb, line 13
def silence_stream(*streams) #:yeild:
  on_hold = streams.collect{ |stream| stream.dup }
  streams.each do |stream|
    stream.reopen(RUBY_PLATFORM =~ /mswin/ ? 'NUL:' : '/dev/null')
    stream.sync = true
  end
  yield
ensure
  streams.each_with_index do |stream, i|
    stream.reopen(on_hold[i])
  end
end
silence_warnings() { || ... } click to toggle source

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

silence_warnings do
  value = noisy_call # no warning voiced
end

noisy_call  # no warning is voiced

CREDIT: David Heinemeier Hansson

# File lib/core/facets/kernel/silence.rb, line 55
def silence_warnings
  old_verbose, $VERBOSE = $VERBOSE, nil
  yield
ensure
  $VERBOSE = old_verbose
end
silently(*streams) { || ... } click to toggle source

Just like #silence_stream, but will default to STDOUT, STDERR if no streams are given.

# File lib/core/facets/kernel/silence.rb, line 39
def silently(*streams) #:yeild:
  streams = [STDOUT, STDERR] if streams.empty?
  silence_stream(*streams){ yield }
end
singleton(&block)

Deprecate?

Alias for: singleton_class
singleton_class(&block) click to toggle source

Easy access to an object's “special” class,

One day these names must be reconciled!

# File lib/core/facets/kernel/singleton_class.rb, line 7
def singleton_class(&block)
  if block_given?
    (class << self; self; end).class_eval(&block)
  else
    (class << self; self; end)
  end
end
Also aliased as: singleton
source_location() click to toggle source
# File lib/core/facets/kernel/source_location.rb, line 5
def source_location
  file, line, meth = *caller(1).first.split(':')
  return file, line
end
super_as(klass=self.class.superclass, *args, &blk) click to toggle source

Like super but skips to a specific ancestor module or class.

class A
  def x ; 1 ; end
end

class B < A
  def x ; 2 ; end
end

class C < B
  def x ; super_as(A) ; end
end

C.new.x  #=> 1
# File lib/core/facets/kernel/as.rb, line 73
def super_as(klass=self.class.superclass, *args, &blk)
  unless self.class.ancestors.include?(klass)
    raise ArgumentError
  end
  called = /\`([^\]+)\/.match(caller(1).first)[1].to_sym
  klass.instance_method(called).bind(self).call(*args,&blk)
end
super_method(klass, meth) click to toggle source

Returns method of a parent class bound to self.

# File lib/core/facets/kernel/as.rb, line 50
def super_method(klass, meth)
  unless self.class.ancestors.include?(klass)
    raise ArgumentError, "Not an ancestor for super_method-- #{klass}"
  end
  klass.instance_method(meth).bind(self)
end
tap() { |self| ... } click to toggle source

The tap K-Combinator. This yields self -and- returns self.

Note, Ruby 1.9+ does not appear to support the zero arity instance_eval option.

# File lib/core/facets/kernel/tap.rb, line 10
def tap(&b)
  if block_given?
    b.arity == 1 ? yield(self) : instance_eval(&b)
  end
  self
end
timed() { |timer = timer.start| ... } click to toggle source

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

# File lib/more/facets/timer.rb, line 268
def timed
  yield( timer = Timer.new.start )
  return timer.total_time
end
to_b() click to toggle source

Boolean conversion for not being nil or false. Other classes may redefine this to suite the particular need.

"abc".to_b   #=> true
true.to_b    #=> true
false.to_b   #=> false
nil.to_b     #=> false
# File lib/core/facets/boolean.rb, line 94
def to_b
  self ? true : false
end
to_yamlfrag() click to toggle source

As with to_yaml but removes the header line (i.e. '—') to create a “YAML fragment”.

# File lib/more/facets/yaml.rb, line 50
def to_yamlfrag
  y = to_yaml
  y.sub!(/---\ */, '')
  y
end
true?() click to toggle source

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

true.true?   #=> true
false.true?  #=> false
nil.true?    #=> false
# File lib/core/facets/boolean.rb, line 105
def true?
  (true == self)
end
try(method, default=nil) click to toggle source

Try a method.

@person ? @person.name : nil

vs

@person.try(:name)

CREDIT: Chris Wanstrath

# File lib/core/facets/kernel/try.rb, line 12
def try(method, default=nil)
  if respond_to? method
    send method
  else
    default
  end
end
val?() click to toggle source

Tests to see if something has value. An object is considered to have value if it is not nil? and if it responds to empty?, is not empty.

nil.val?     #=> false
[].val?      #=> false
10.val?      #=> true
[nil].val?   #=> true
# File lib/core/facets/kernel/val.rb, line 12
def val?
  return false if nil?
  return false if empty? if respond_to?(:empty?)
  true
end
with(obj=self, &block) click to toggle source

Like returning but exectues the block via instance_eval.

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

foo # => ['bar', 'baz']
# File lib/core/facets/kernel/with.rb, line 15
def with(obj=self, &block)
  obj.instance_eval(&block)
end
yaml(*args,&blk) click to toggle source

Convenience method for loading YAML.

# File lib/more/facets/yaml.rb, line 44
def yaml(*args,&blk)
  YAML.load(*args,&blk)
end