Advertisement
Guest User

Untitled

a guest
Sep 9th, 2015
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.93 KB | None | 0 0
  1. #!perl6
  2.  
  3. class Person { ... }
  4. class Thing { ... }
  5. class Container { ... }
  6. class Place { ... }
  7. class Nowhere { ... }
  8.  
  9. class Entity {
  10. use JSON::Tiny;
  11. my %cache;
  12.  
  13. has $.id is rw;
  14.  
  15. method Str { self.id }
  16.  
  17. method load(Entity: $id) {
  18. return Nowhere if $id eq 'nowhere';
  19. return %cache{$id} if %cache{$id}:exists;
  20.  
  21. my %hash = from-json slurp "$id.json";
  22. my $class = %hash<class>:delete;
  23.  
  24. if (%hash<location>:exists) {
  25. %hash<location> = Entity.load(%hash<location>);
  26. }
  27. %hash<id> = $id;
  28.  
  29. %cache{$id} = sub ($_) {
  30. return Person.new(|%hash) when 'Person';
  31. return Place.new(|%hash) when 'Place';
  32. return Container.new(|%hash) when 'Container';
  33. return Thing.new(|%hash) when 'Thing';
  34. }($class);
  35. warn "still here";
  36.  
  37. return %cache{$id};
  38. }
  39.  
  40. method json {
  41. my %hash;
  42. for self.^attributes -> $a {
  43. try {
  44. # Fails on undefined $.location, with
  45. # «Invocant requires an instance of type <anon>, but a type object was passed.
  46. # Did you forget a .new?»
  47. %hash{ $a.Str.substr(2) } = $a.get_value(self).Str
  48. }
  49. };
  50. %hash<class> = self.^name;
  51. return to-json %hash;
  52. }
  53. }
  54.  
  55. class Place is Entity {
  56. has Entity $.location is rw where Place;
  57. }
  58.  
  59. class Person is Entity {
  60. has Entity $.location is rw where Place = Nowhere;
  61. }
  62.  
  63. class Container is Entity {
  64. has Entity $.location is rw where Place|Container = Nowhere;
  65. }
  66.  
  67. class Thing is Entity {
  68. has Entity $.location is rw where Place|Container|Person = Nowhere;
  69. }
  70.  
  71. class Nowhere is Place {
  72. submethod Str { "nowhere" }
  73. }
  74.  
  75.  
  76. #my $t = Thing.new;
  77. my $t = Entity.load("foo");
  78. #$t.location = Place.new(id => "lhq");
  79. say $t.perl;
  80. say $t.json;
  81. say $t.location.json;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement