Browse Source

Add a few meta programming source files

master
Peter J. Jones 9 years ago
parent
commit
9f19fa9c54
2 changed files with 67 additions and 0 deletions
  1. 29
    0
      source/meta/class_var.rb
  2. 38
    0
      source/meta/singleton_var.rb

+ 29
- 0
source/meta/class_var.rb View File

@@ -0,0 +1,29 @@
class Base
def var () @@var end
def var= (x) @@var = x end
end

class A < Base; end
class B < Base; end

a = A.new
b = B.new
a.var = 'A'
b.var = 'B'
a.var # =>
b.var # =>

################################################################################
require('test/unit')

################################################################################
class ClassVarTest < Test::Unit::TestCase
def test_class_var
a = A.new
b = B.new
a.var = 'A'
b.var = 'B'
assert_equal('B', a.var)
assert_equal('B', b.var)
end
end

+ 38
- 0
source/meta/singleton_var.rb View File

@@ -0,0 +1,38 @@
class Base
def var
class << self.class
self
end.instance_eval {@var}
end
def var= (x)
class << self.class
self
end.instance_eval {@var = x}
end
end

class A < Base; end
class B < Base; end

a = A.new
b = B.new
a.var = 'A'
b.var = 'B'
a.var # =>
b.var # =>

################################################################################
require('test/unit')

################################################################################
class SingletonVarTest < Test::Unit::TestCase
def test_singleton_var
a = A.new
b = B.new
a.var = 'A'
b.var = 'B'
assert_equal('A', a.var)
assert_equal('B', b.var)
end
end

Loading…
Cancel
Save