Skip to content

Instantly share code, notes, and snippets.

@beppu
Created October 15, 2009 21:33
Show Gist options
  • Select an option

  • Save beppu/211311 to your computer and use it in GitHub Desktop.

Select an option

Save beppu/211311 to your computer and use it in GitHub Desktop.
#!/usr/bin/env perl
use strict;
use warnings;
# Inheritance Hierarchy
#
# A
# \
# B
# \
# C
#
# Problem
#
# A, B, and C can all have relations.
# This is stored in A's class data.
# C->relations should evaluate to
# C's relations, B's relations, and A's relations.
#
# Solution
#
# Implement the relations() method once in A.
# Also implement a parents() method in A that can walk up @ISA.
# Make relations() use parents() method.
#______________________________________
package A;
our %rels = (
A => [
"has_many 'foo'",
"has_many 'bar'",
],
B => [
"has_a 'bucket'",
],
C => [
"has_a 'cheezburger'",
],
);
sub parents {
my $class = shift;
no strict 'refs';
if (@{$class."::ISA"}) {
my ($parent) = @{$class."::ISA"}; # BUG: single-inheritance-only
return $class, $parent->parents;
} else {
return $class;
}
}
sub relations {
my $class = shift;
my @relations;
for ($class->parents) {
push @relations, { $_ => $rels{$_} }
}
@relations;
}
#______________________________________
package B;
our @ISA = qw(A);
#______________________________________
package C;
our @ISA = qw(B);
#_____________________________________________________________________________
package main;
use Data::Dump 'pp';
warn pp(C->parents);
warn pp(C->relations);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment