Created
February 24, 2009 21:16
-
-
Save AndrewO/69792 to your computer and use it in GitHub Desktop.
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
require 'test/unit' | |
class SubsectionGraph | |
# This gives us access to the class's singleton object which will sit between the actual Class structure and | |
# any instances and child classes | |
# | |
# If you're using metaid, this can be replaced by something like: | |
# meta_eval do | |
# def prefix(p = nil) | |
# ... | |
# end | |
# end | |
class << self | |
def prefix(p = nil) | |
# Being used as a reader to return the existing one | |
return @prefix unless p | |
# Use an instance variable, but it's an instance variable of a Class object | |
@prefix = p | |
end | |
end | |
def initialize(num) | |
@num = num | |
end | |
def full_name | |
# It sees prefix (as defined above) as a class method, even though it's on the singleton/meta class. | |
"#{self.class.prefix}-#{@num.to_s}" | |
end | |
end | |
class FooGraph < SubsectionGraph | |
prefix "foo" | |
end | |
class BarGraph < SubsectionGraph | |
prefix "bar" | |
end | |
# A little test to make sure this actually works | |
class MetaTest < Test::Unit::TestCase | |
def setup | |
@foo = FooGraph.new(25) | |
@bar = BarGraph.new(30) | |
end | |
def test_full_names | |
assert_equal("foo-25", @foo.full_name) | |
assert_equal("bar-30", @bar.full_name) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment