1 package Object::Builder;
3 use Module::Runtime qw(use_module);
4 use List::Util qw(reduce);
5 use Scalar::Util qw(weaken);
8 our $VERSION = '0.000001'; # 0.0.1
10 $VERSION = eval $VERSION;
13 is => 'rw', lazy => 1, builder => 1,
14 trigger => sub { shift->_clear_final_class },
17 sub _build_class { die "No default class set" }
20 is => 'rw', lazy => 1, builder => 1, clearer => 1,
21 trigger => sub { shift->_clear_final_class },
22 coerce => sub { ref($_[0]) eq 'ARRAY' ? { '' => $_[0] } : $_[0] },
26 my ($self, $for, @roles) = @_;
27 $self->roles({ %{$self->roles}, $for => \@roles });
31 after clear_roles => sub { shift->_clear_final_class };
33 sub _build_roles { {} }
37 my $roles = $self->roles;
38 map @{$roles->{$_}}, sort keys %$roles;
41 has _final_class => (is => 'lazy', clearer => 1);
43 sub _build__final_class {
45 my $class = use_module($self->class);
46 if (my @roles = $self->_role_list) {
48 return Moo::Role->create_class_with_roles($class, @roles);
54 after _clear_final_class => sub { shift->clear_object };
56 has constructor => (is => 'ro', default => sub { 'new' });
59 is => 'rw', builder => 1, clearer => 1,
60 trigger => sub { shift->_clear_final_arguments },
64 my ($self, $name, @arg) = @_;
65 $self->arguments({ %{$self->arguments}, $name => \@arg });
68 sub set_argument_weaken {
69 my ($self, $name, @arg) = @_;
71 $self->arguments({ %{$self->arguments}, $name => \@arg });
74 sub _build_arguments { {} }
76 after clear_arguments => sub { shift->_clear_final_arguments };
78 has _final_arguments => (is => 'lazy', clearer => 1);
80 after _clear_final_arguments => sub { shift->clear_object };
82 sub _build__final_arguments {
84 my %arguments = %{$self->arguments};
85 map +($_ => $self->_resolve($arguments{$_})), keys %arguments;
89 my ($self, $to_resolve) = @_;
92 # [ $inv, 'x', 'y' ] -> $inv->x->y
93 # [ $inv, [ 'x', 'y' ], 'z' ] -> $inv->x('y')->z
96 my ($meth, @arg) = (ref($b) eq 'ARRAY' ? @$b : $b);
101 has object => (is => 'lazy', clearer => 1);
105 $self->_final_class->${\$self->constructor}($self->_final_arguments);
110 $self->_build_object;
114 my ($self, $args) = @_;
116 $args->{object} or $args->{class}
117 or ($self->can('_build_class') ne __PACKAGE__->can('_build_class')
119 die "No static object passed, and no class supplied or defaulted";
127 Object::Builder - An object for building other objects.
135 mst - Matt S. Trout (cpan:MSTROUT) <mst@shadowcat.co.uk>
139 None yet - maybe this software is perfect! (ahahahahahahahahaha)
143 Copyright (c) 2012 the Object::Builder L</AUTHOR> and L</CONTRIBUTORS>
148 This library is free software and may be distributed under the same terms