- Bit
- __DIR__
- __HERE__
- __callee__
- __method__
- as
- ask
- attr_singleton_accessor
- attr_singleton_reader
- attr_singleton_writer
- blank?
- bool?
- callstack
- complete
- constant
- d
- deep_copy
- demo
- eigenclass
- enable_warnings
- ergo
- false?
- in?
- instance_assign
- instance_class
- instance_exec
- instance_values
- load_local
- maybe
- meta_alias
- meta_class
- meta_def
- meta_eval
- metaclass
- non_nil?
- not_nil?
- object_hexid
- object_send
- p
- populate
- require_all
- require_local
- resc
- respond
- respond_with_value
- returning
- send_as
- set_from
- silence_stream
- silence_warnings
- singleton
- singleton_class
- singleton_class
- super_as
- super_method
- suppress
- tap
- to_b
- true?
- try
- val?
- with
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 CREDIT: George Moschovitis
[ show source ]
# File lib/facets/bitmask.rb, line 100 def Bit(n) 1 << Integer(n) end
Similar to FILE and LINE, DIR provides the directory path to the current executing script.
CREDIT: Trans
[ show source ]
# File lib/facets/kernel/__dir__.rb, line 8 def __DIR__ (/^(.+)?:\d+/ =~ caller[0]) ? File.dirname($1) : nil end
[ show source ]
# File lib/facets/kernel/d.rb, line 3 def __HERE__ "#{__FILE__}: #{__LINE__}" end
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
[ show source ]
# File lib/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
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".
[ show source ]
# File lib/facets/kernel/ask.rb, line 19 def ask(question, answers=nil) $stdout << "#{question}" $stdout << " [#{answers}] " if answers until inp = $stdin.gets ; sleep 1 ; end ; puts inp.strip end
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
[ show source ]
# File lib/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
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
[ show source ]
# File lib/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
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
[ show source ]
# File lib/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
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?
[ show source ]
# File lib/facets/blank.rb, line 14 def blank? respond_to?(:empty?) ? empty? : !self end
Returns true is an object is class TrueClass or FalseClass, otherwise false.
true.bool? #=> true false.bool? #=> true nil.bool? #=> false
[ show source ]
# File lib/facets/boolean.rb, line 127 def bool? (true == self or false == self) end
Parse a caller string and break it into its components, returning an array. Returns:
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
[ show source ]
# File lib/facets/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
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
[ show source ]
# File lib/facets/kernel/complete.rb, line 13 def complete loop { break unless yield } end
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
[ show source ]
# File lib/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
Like p but gives file and line number.
d("hi")
produces
/home/dave/projects/foo.rb, 38 "hi"
TODO: This is borderline "prime". Keep here?
Another copy of it exits in dtools.rb
[ show source ]
# File lib/facets/kernel/d.rb, line 19 def d(*x) puts "#{__FILE__}, #{__LINE__}" x.each{ |e| puts e.inspect } #p(*x) x.size > 1 ? x : x.last #x.last end
Anything that can be marshaled can be copied in totality. This is also commonly called a deep_copy.
"ABC".copy #=> "ABC"
[ show source ]
# File lib/facets/kernel/deep_copy.rb, line 8 def deep_copy Marshal::load(Marshal::dump(self)) end
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]
TODO: Is there a way to do this without the eval string in block?
Preferably just a block and no string.
[ show source ]
# File lib/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
During this trying time when no one can get their techie catchwords to stick to the refrigerator no matter how hard they slap it # with the enchanted magnetic spatula, it’s good to know that the contrived phrases really do fly, graceful and unclasped and bearing north toward chilled shrimp. I know what my Hallowe’en pumpkin is going to say.
-- why the lucky stiff
CREDIT: WhyTheLuckyStiff
[ show source ]
# File lib/facets/metaid.rb, line 82 def eigenclass (class << self; self; end) end
Sets $VERBOSE to true for the duration of the block and back to its original value afterwards.
CREDIT: David Heinemeier Hansson
[ show source ]
# File lib/facets/kernel/silence.rb, line 51 def enable_warnings old_verbose, $VERBOSE = $VERBOSE, true yield ensure $VERBOSE = old_verbose end
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
[ show source ]
# File lib/facets/kernel/ergo.rb, line 17 def ergo &b if block_given? b.arity == 1 ? yield(self) : instance_eval(&b) else self end end
Returns true is an object is class FalseClass, otherwise false.
true.false? #=> false false.false? #=> true nil.false? #=> false
[ show source ]
# File lib/facets/boolean.rb, line 116 def false? (false == self) end
Is self included in other?
5.in?(0..10) #=> true 5.in?([0,1,2,3]) #=> false
[ show source ]
# File lib/facets/kernel/in.rb, line 8 def in?(other) other.include?(self) end
Set instance variables using a hash.
instance_assign('@a'=>1, '@b'=>2)
@a #=> 1
@b #=> 2
[ show source ]
# File lib/facets/kernel/instance.rb, line 58 def instance_assign(hargs) hargs.each do |k,v| k = "@#{k}" if k !~ /^@/ instance_variable_set(k, v) end return self end
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.
CREDIT: Trans
[ show source ]
# File lib/facets/kernel/instance.rb, line 21 def instance_class(&block) (class << self; self; end).module_eval(&block) if block (class << self; self; end) end
Like instance_eval but allows parameters to be passed.
NOTE: This is deprecated b/c implementation is fragile. Use Ruby 1.9 instead.
[ show source ]
# File lib/facets/kernel/instance_exec.rb, line 12 def instance_exec(*arguments, &block) block.bind(self)[*arguments] end
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 #=> [1,2]
CREDIT: David Heinemeier Hansson
[ show source ]
# File lib/facets/kernel/instance.rb, line 40 def instance_values instance_variables.inject({}) do |values, name| values[name[1..-1]] = instance_variable_get(name) values end end
Load file from same dir as calling script.
load_local 'templib'
[ show source ]
# File lib/facets/kernel/load.rb, line 7 def load_local(fname, safe=nil) #fdir = File.expand_path( File.dirname( caller[0] ) ) fdir = File.dirname( caller[0] ) load( File.join( fdir, fname ), safe ) end
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
[ show source ]
# File lib/facets/kernel/maybe.rb, line 9 def maybe(chance = 0.5, &block) if block then yield if rand < chance else rand < chance end end
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
[ show source ]
# File lib/facets/metaid.rb, line 11 def meta_alias(*args) meta_class do alias_method(*args) end end
[ show source ]
# File lib/facets/metaid.rb, line 47 def meta_class(&block) if block_given? (class << self; self; end).class_eval(&block) else (class << self; self; end) end end
Add method to a meta-class —i.e. a singleton method.
class X; end
X.meta_def(:x){"x"}
X.x #=> "x"
CREDIT: WhyTheLuckyStiff
[ show source ]
# File lib/facets/metaid.rb, line 38 def meta_def( name, &block ) meta_class do define_method( name, &block ) end end
Evaluate code in a metaclass. This is equivalent to ‘meta_class.instance_eval’.
CREDIT: WhyTheLuckyStiff
[ show source ]
# File lib/facets/metaid.rb, line 22 def meta_eval(str=nil, &blk) if str meta_class.instance_eval(str) else meta_class.instance_eval(&blk) end end
Alias for meta_class
The opposite of nil?.
"hello".not_nil? # -> true nil.not_nil? # -> false CREDIT: Gavin Sinclair
[ show source ]
# File lib/facets/kernel/not_nil.rb, line 10 def not_nil? not nil? end
Returns the object id as a string in hexideciaml, which is how Ruby reports them with inspect.
"ABC".object_hexid #=> "0x402d359c"
[ show source ]
# File lib/facets/kernel/object.rb, line 48 def object_hexid return "0x" << ('%.x' % (2*self.__id__)) #[1..-1] end
Send only to public methods.
class X
private
def foo; end
end
X.new.object_send(:foo)
=> NoMethodError: private method `foo' called for #<X:0xb7ac6ba8>
TODO: object_send needs to change for 1.9.
CREDIT: Trans
[ show source ]
# File lib/facets/kernel/object.rb, line 32 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) method_missing(name,*args,&blk) #else # raise NoMethodError end end
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
DEPRECATE AS OF 1.9, if p will then do this too.
[ show source ]
# File lib/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
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.
TODO: Better name, set_with ?
[ show source ]
# File lib/facets/kernel/populate.rb, line 25 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
Require a pattern of files. This make is easy to require an entire directory, for instance.
require_all 'facets/time/*'
[ show source ]
# File lib/facets/kernel/load.rb, line 28 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 file from same dir as calling script.
require_local 'templib'
[ show source ]
# File lib/facets/kernel/load.rb, line 17 def require_local(fname) #fdir = File.expand_path( File.dirname( caller[0] ) ) fdir = File.dirname( caller[0] ) require( File.join( fdir, fname ) ) end
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
[ show source ]
# File lib/facets/kernel/resc.rb, line 11 def resc(str) Regexp.escape(str.to_s) end
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
[ show source ]
# File lib/facets/kernel/respond.rb, line 16 def respond(sym, *args) return nil if not respond_to?(sym) send(sym, *args) end
Alias for respond
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
[ show source ]
# File lib/facets/kernel/returning.rb, line 18 def returning(obj=self) #:yield: yield obj obj end
Call parent class/module methods once bound to self.
TODO: Does this have the proper scope for send?
[ show source ]
# File lib/facets/kernel/as.rb, line 36 def send_as(ancestor, sym, *args, &blk) ancestor.instance_method(sym).bind(self).call(*args,&blk) end
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: pepulate_from(obj) ?
[ show source ]
# File lib/facets/kernel/populate.rb, line 54 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
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
[ show source ]
# File lib/facets/kernel/silence.rb, line 13 def silence_stream(stream) old_stream = stream.dup stream.reopen(RUBY_PLATFORM =~ /mswin/ ? 'NUL:' : '/dev/null') stream.sync = true yield ensure stream.reopen(old_stream) end
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
[ show source ]
# File lib/facets/kernel/silence.rb, line 39 def silence_warnings old_verbose, $VERBOSE = $VERBOSE, nil yield ensure $VERBOSE = old_verbose end
Access to an object‘s "special" class, otherwise known as it‘s eigenclass or metaclass, etc.
One day these names must be reconciled!
[ show source ]
# File lib/facets/metaid.rb, line 62 def singleton (class << self; self; end) end
Easy access to an object‘s "special" class, otherwise known as it‘s eigen or meta class.
[ show source ]
# File lib/facets/kernel/singleton_class.rb, line 6 def singleton_class(&block) if block_given? (class << self; self; end).class_eval(&block) else (class << self; self; end) end end
[ show source ]
# File lib/facets/metaid.rb, line 66 def singleton_class (class << self; self; end) end
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
[ show source ]
# File lib/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
Returns method of a parent class bound to self.
[ show source ]
# File lib/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
Supress errors while executing a block, with execptions.
CREDIT: David Heinemeier Hansson
[ show source ]
# File lib/facets/kernel/silence.rb, line 62 def suppress(*exception_classes) begin yield rescue Exception => e raise unless exception_classes.any? { |cls| e.kind_of?(cls) } end end
The tap K-Combinator. This yields self -and- returns self.
[ show source ]
# File lib/facets/ruby.rb, line 265 def tap(&b) if block_given? b.arity == 1 ? yield(self) : instance_eval(&b) end self end
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
[ show source ]
# File lib/facets/boolean.rb, line 94 def to_b self ? true : false end
Returns true is an object is class TrueClass, otherwise false.
true.true? #=> true false.true? #=> false nil.true? #=> false
[ show source ]
# File lib/facets/boolean.rb, line 105 def true? (true == self) end
Try a method.
@person ? @person.name : nil
vs
@person.try(:name) CREDIT: Chris Wanstrath
[ show source ]
# File lib/facets/kernel/try.rb, line 10 def try(method, default=nil) if respond_to? method send method else default end end
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
[ show source ]
# File lib/facets/kernel/val.rb, line 12 def val? return false if nil? return false if empty? if respond_to?(:empty?) true end
Like returning but exectures the block via instance_eval.
def foo
with values = [] do
self << 'bar'
self << 'baz'
end
end
foo # => ['bar', 'baz']
[ show source ]
# File lib/facets/kernel/with.rb, line 15 def with(obj=self, &block) obj.instance_eval &block end
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+.
[ show source ]
# File lib/facets/ruby.rb, line 309 def __callee__ /\`([^\']+)\'/.match(caller(1).first)[1].to_sym end
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+.
[ show source ]
# File lib/facets/ruby.rb, line 296 def __method__ /\`([^\']+)\'/.match(caller(1).first)[1].to_sym end