Created
August 31, 2011 11:23
-
-
Save damncabbage/1183334 to your computer and use it in GitHub Desktop.
Ruby Metaprogramming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Regarding https://gist.github.com/1180947 | |
# | |
require 'test/unit' | |
# Example classes | |
class Animal; end | |
class Dog < Animal | |
attr_accessor :name | |
def initialize(name=nil) | |
self.name = name | |
end | |
end | |
# Tests | |
class TestAnimal < Test::Unit::TestCase | |
def test_register_property | |
dog = Dog.new | |
Dog.class_eval do | |
attr_accessor :no | |
end | |
assert_respond_to dog, :no | |
end | |
def test_register_method | |
beethoven = Dog.new('Beethoven') | |
Dog.class_eval do | |
def speak | |
"Hello I'm #{name}" | |
end | |
end | |
assert_respond_to beethoven, :speak | |
assert_equal "Hello I'm Beethoven", beethoven.speak | |
end | |
def test_extend_with_something_that_kinda_looks_like_a_hash_map | |
beethoven = Dog.new('Beethoven') | |
Dog.class_eval do | |
{ | |
:bark => proc { "Woof! Woof!" }, | |
:is_named => proc { |name| self.name == name } | |
}.each do |method,block| | |
self.send(:define_method, method, block) | |
end | |
end | |
assert !beethoven.is_named("Johnny") | |
assert_equal 'Woof! Woof!', beethoven.bark | |
end | |
def test_inheritance | |
beethoven = Dog.new('Beethoven') | |
Animal.class_eval do | |
def foo | |
'bar' | |
end | |
end | |
# Couldn't exactly figure out why the PHP tests were | |
# assetFalse(); was that just to make the tests pass? | |
assert_respond_to beethoven, :foo | |
assert_not_equal Animal, Dog | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The last test in my gist, should assert that the
Dog
andAnimal
Classes do not have the same MetaClass, so thatmethods added to the
Dog
class do not end up accessible from theAnimal
class.Though this test fails in the current implementation. Maybe I'll look into it when I've more time.