lib/facet/kernel/as.rb in facets-0.9.0 vs lib/facet/kernel/as.rb in facets-1.0.0

- old
+ new

@@ -1,90 +1,180 @@ -require 'nano/kernel/as.rb' \ No newline at end of file + +begin + require 'calibre/functor.rb' +rescue LoadError + require 'facet/functor.rb' +end + +module Kernel + + # Returns a Functor that allows one to call any parent method directly. + # + # 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 + # + def as( klass=nil, &blk ) + selfclass = Kernel.instance_method(:class).bind(self).call + klass ||= selfclass.superclass + if selfclass.ancestors.include?(klass) + Functor.new do |meth, *args| # &blk| + klass.instance_method(meth).bind(self).call(*args) # ,&blk) + end + else + raise ArgumentError, "#{klass} is not an ancestor" + end + end + +=begin + def as( role, &blk ) + unless role.is_a?(Class) + role = self.class.const_get( role ) + end + @roles ||= {} + @roles[role] ||= role.allocate + robj = @roles[role] + robj.assign_from( self ) + result = robj.instance_eval( &blk ) + self.assign_from( robj ) # w/o this much like namespaces + result + end +=end + +end + + + +# _____ _ +# |_ _|__ ___| |_ +# | |/ _ \/ __| __| +# | | __/\__ \ |_ +# |_|\___||___/\__| +# +=begin test + + require 'test/unit' + + class TCKernel < Test::Unit::TestCase + class A + def x; "A.x"; end + def y; "A.y"; end + end + class B < A + def x; "B.x" end + def y; "B.y" end + end + class C < B + def x; "C.x"; end + def y; as.x ; end + end + + def setup + @c = C.new + end + + def test_as + assert_equal("B.x", @c.y) + assert_equal("C.x", @c.x) + end + end + +=end