in reply to Re^2: Enumerating all attributes of a Moo object
in thread Enumerating all attributes of a Moo object
I'll also point out a technique you could use. Instead of FooFactory introspecting class Foo, you could have class Foo pass FooFactory all the information it needs. One simple way to do that is write a wrapper for has...
#!/usr/bin/env perl use v5.14; use Data::Dumper; package FooFactory { use Moo; has name => (is => "ro", required => 1); our @known_attributes; sub build_foo { my $self = shift; my %params = @_; my %attrs; for (@known_attributes) { $attrs{$_} = $params{$_} if exists $params{$_}; } 'Foo'->new(%attrs, maker => $self); } } package Foo { use Moo; sub my_has { my ($attr, %spec) = @_; # Inform FooFactory of the new attribute # Note we're ignoring init_arg for this simple example. push @FooFactory::known_attributes, $attr; has($attr, %spec); } my_has foo => (is => "ro"); my_has bar => (is => "ro"); my_has baz => (is => "ro"); my_has maker => (is => "ro"); } my $factory = 'FooFactory'->new(name => "Acme Inc"); my $obj = $factory->build_foo(bar => 42); print Dumper($obj);
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: Enumerating all attributes of a Moo object
by McA (Priest) on Jul 09, 2013 at 08:53 UTC |