Skip to content

Instantly share code, notes, and snippets.

@damncabbage
Created August 31, 2011 11:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save damncabbage/1183334 to your computer and use it in GitHub Desktop.
Save damncabbage/1183334 to your computer and use it in GitHub Desktop.
Ruby Metaprogramming
#
# 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
@CHH
Copy link

CHH commented Aug 31, 2011

The last test in my gist, should assert that the Dog and Animal Classes do not have the same MetaClass, so that
methods added to the Dog class do not end up accessible from the Animal class.

Though this test fails in the current implementation. Maybe I'll look into it when I've more time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment