Module: Rpub::SubclassTracker
Overview
Add tracking of subclasses to an existing class by extending it with SubclassTracker.
This allows you to set an identifier in a subclass using the identifier
macro, and find subclasses based on that value.
Example:
class ParentClass
extend SubclassTracker
end
class ChildClass < ParentClass
identifier 'foo'
end
ParentClass.matching('foo') # => ChildClass
ParentClass.matching('bar') # => raises SubclassTracker::NoSuchSubclass
Note that you don’t HAVE to set an identifier. If you don’t, your child class will never be found by #matching
.
Defined Under Namespace
Classes: NoSuchSubclass
Instance Method Summary collapse
- #each ⇒ Object
-
#identifier(id = nil) ⇒ Object
Set or return the identifier for this class.
- #inherited(child) ⇒ Object
- #matching(identifier) ⇒ Object
Instance Method Details
#each ⇒ Object
42 43 44 45 |
# File 'lib/rpub/subclass_tracker.rb', line 42 def each @subclasses ||= [] @subclasses.each { |subclass| yield subclass } end |
#identifier(id = nil) ⇒ Object
Set or return the identifier for this class.
31 32 33 34 |
# File 'lib/rpub/subclass_tracker.rb', line 31 def identifier(id = nil) return @identifier if id.nil? @identifier = id end |
#inherited(child) ⇒ Object
36 37 38 39 40 |
# File 'lib/rpub/subclass_tracker.rb', line 36 def inherited(child) @subclasses ||= [] @subclasses << child super end |
#matching(identifier) ⇒ Object
47 48 49 |
# File 'lib/rpub/subclass_tracker.rb', line 47 def matching(identifier) find { |subclass| subclass.identifier === identifier } or raise NoSuchSubclass, identifier end |