Skip to content

Instantly share code, notes, and snippets.

@timo
Created September 17, 2024 15:12
Show Gist options
  • Select an option

  • Save timo/2aa2a740fba4efcaba6fa7ee3d337e1c to your computer and use it in GitHub Desktop.

Select an option

Save timo/2aa2a740fba4efcaba6fa7ee3d337e1c to your computer and use it in GitHub Desktop.
silly metaprogramming approach to declaratively unmarshaling json (or similar) into objects
role ArrayOf[::Thing] {
method COERCE(*@in) {
Thing.HOW ~~ Metamodel::ClassHOW
?? (Array but ArrayOf[Thing]).new(do Thing.new(|%$_) for @in)
!! (Array but ArrayOf[Thing]).new(do Thing($_) for @in);
}
}
class Address { has $.address; has $.ifname; };
class Route { has $.dev; has $.dst; };
class Ip is rw {
has ArrayOf[Address]() $.a;
has ArrayOf[Route]() $.r;
}
say Ip.new(
a => [%( :999address, :ifname<eth0> ), %( :123address, :ifname<wlp0> )],
r => [%( :dst<default>, :dev<eth0> ), %( :dst<127.0.0.1>, :dev<lo> )]
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment