Skip to content

Instantly share code, notes, and snippets.

@Juerd

Juerd/Entity.pm Secret

Created June 2, 2017 02:20
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 Juerd/27947ac0e75650cec92f16abf69011fd to your computer and use it in GitHub Desktop.
Save Juerd/27947ac0e75650cec92f16abf69011fd to your computer and use it in GitHub Desktop.
class Nowhere { ... }
class Entity {
use JSON::Tiny;
my %cache;
has $.id is rw;
multi method Str (Entity:D: ) { self.id }
sub _load($id --> Entity) {
return Nowhere if $id eq 'nowhere';
return %cache{$id} if %cache{$id}:exists;
my $io = "$id.json".IO;
$io.r or return;
my $json = try $io.slurp or return;
my %hash = from-json $json;
my $class = %hash<class>:delete;
if (%hash<location>:exists) {
%hash<location> = Entity.load(%hash<location>);
}
%hash<id> = $id;
$class ~~ /^ [ Thing | Container | Person | Place ] $/
or die "Invalid class '$class' for $id";
return %cache{$id} = ::($class).new(|%hash);
}
method load($id --> Entity) {
return _load($id);
}
method store {
spurt $.id ~ ".json", $.json;
}
method json {
my %hash;
for self.^attributes -> $a {
my $value = $a.get_value(self);
if (defined $value) {
$value = ~$value if $value.isa(Entity);
%hash{ $a.Str.substr(2) } = $value;
}
};
%hash<class> = self.^name;
return to-json %hash;
}
method would-recurse (Mu $to-be-contained) {
say self;
say $to-be-contained;
die;
return 0;
}
}
role Location { }
role Lendable {
has Location $.location = Nowhere;
has @.location_history;
method is-at(Location $new) {
$!location = $new;
@!location_history.push({ dt => ~DateTime.now, location => ~$new });
}
}
class Person is Entity does Location { }
class Place is Entity does Location { }
class Nowhere is Entity does Location { method Str { "nowhere" } }
class Thing is Entity does Lendable { }
class Container is Entity does Lendable does Location { }
@araraloren
Copy link

araraloren commented Jun 2, 2017

role Location { ... }
class Nowhere does Location { ... }

@Juerd
Copy link
Author

Juerd commented Jun 2, 2017

Thanks. However, changing that doesn't fix the issue. :(

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