Last active
December 19, 2015 12:18
-
-
Save rmg/5953543 to your computer and use it in GitHub Desktop.
Lineage: Tap into the latent enumerable powers of your class's directed graph!
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 'set' | |
def Lineage(enum_name = :lineage, parent_accessor = :parent) | |
Module.new do | |
define_method enum_name do |&block| | |
if block.nil? | |
enum_for(enum_name) | |
else | |
next_parent, visited = self, Set[self] | |
while next_parent = next_parent.send(parent_accessor) | |
if visited.include? next_parent | |
raise "Cycle detected!" | |
end | |
block.yield next_parent | |
visited << next_parent | |
end | |
end | |
end | |
end | |
end | |
module Lineage | |
include Lineage() | |
end |
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
# A simple example | |
class Person < Struct.new(:name, :parent) | |
include Lineage | |
end | |
youngest = Person.new("Adam", nil) | |
(1..10).each do |n| | |
youngest = Person.new(n.to_s, youngest) | |
end | |
youngest.name #=> "10" | |
youngest.lineage.map(&:name) #=> ["9", "8", "7", "6", "5", "4", "3", "2", "1", "Adam"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The
#lineage
method this mixin provides yields or returns anEnumerator
, which lets you do all the cool enumeration stuff likemap
,reduce
,select
,each
,to_a
, etc..