Skip to content

Instantly share code, notes, and snippets.

@nbfritz
Last active August 29, 2015 14:04
Show Gist options
  • Save nbfritz/b7980a19194095fae593 to your computer and use it in GitHub Desktop.
Save nbfritz/b7980a19194095fae593 to your computer and use it in GitHub Desktop.
Interesting experimentation with ruby metaclasses
require 'minitest/autorun'
class Monkey
@@m1 = "monkey"
class << self
attr_accessor :m2
end
def self.m1=(m)
@@m1 = m
end
def self.m1
@@m1
end
end
class Chimp < Monkey
@@m1 = "chimp"
end
class Spidermonkey < Monkey
@@m1 = "spidermonkey"
end
class TestTheory < Minitest::Test
def test_m1_is_at_at_m1
Monkey.m1 = "m1"
assert_equal "m1", Monkey.class_variable_get(:@@m1)
end
def test_m2_is_not_at_at_m1
Monkey.m2 = "m2"
refute_equal "m2", Monkey.class_variable_get(:@@m1)
end
def test_m2_is_not_m1
Monkey.m2 = "m2"
Monkey.m1 = "m1"
assert_equal "m2", Monkey.m2
end
def test_monkey_m1_is_inherited
Monkey.m1 = "monkey"
Spidermonkey.m1 = "spidermonkey"
Chimp.m1 = "chimp"
assert_equal "chimp", Monkey.m1
assert_equal "chimp", Chimp.m1
assert_equal "chimp", Spidermonkey.m1
end
def test_monkey_m2_is_not_inherited
Monkey.m2 = "monkey"
Spidermonkey.m2 = "spidermonkey"
Chimp.m2 = "chimp"
assert_equal "monkey", Monkey.m2
assert_equal "chimp", Chimp.m2
assert_equal "spidermonkey", Spidermonkey.m2
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment