6 Moose::Cookbook::Extending::Recipe4 - Acting like Moose.pm and providing sugar Moose-style
10 package MyApp::Mooseish;
18 Moose::Exporter->setup_import_methods(
19 with_caller => ['has_table'],
25 return Moose->init_meta( @_, metaclass => 'MyApp::Meta::Class' );
30 $caller->meta->table(shift);
33 package MyApp::Meta::Class;
36 extends 'Moose::Meta::Class';
38 has 'table' => ( is => 'rw' );
42 This recipe expands on the use of L<Moose::Exporter> we saw in
43 L<Moose::Cookbook::Extending::Recipe1>. Instead of providing our own
44 object base class, we provide our own metaclass class, and we also
45 export a C<has_table> sugar function.
47 Given the above code, you can now replace all instances of C<use
48 Moose> with C<use MyApp::Mooseish>. Similarly, C<no Moose> is now
49 replaced with C<no MyApp::Mooseish>.
51 The C<with_caller> parameter specifies a list of functions that should
52 be wrapped before exporting. The wrapper simply ensures that the
53 importing package name is the first argument to the function, so we
54 can do C<S<my $caller = shift;>>.
56 See the L<Moose::Exporter> docs for more details on its API.
58 =head1 USING MyApp::Mooseish
60 The purpose of all this code is to provide a Moose-like
61 interface. Here's what it would look like in actual use:
69 has 'username' => ( is => 'ro' );
70 has 'password' => ( is => 'ro' );
76 All of the normal Moose sugar (C<has()>, C<with()>, etc) is available
77 when you C<use MyApp::Mooseish>.
81 Providing sugar functions can make your extension look much more
82 Moose-ish. See L<Fey::ORM> for a more extensive example.
86 Dave Rolsky E<lt>autarch@urth.orgE<gt>
88 =head1 COPYRIGHT AND LICENSE
90 Copyright 2006-2009 by Infinity Interactive, Inc.
92 L<http://www.iinteractive.com>
94 This library is free software; you can redistribute it and/or modify
95 it under the same terms as Perl itself.
103 MyApp::Mooseish->import;
107 has( 'username' => ( is => 'ro' ) );
108 has( 'password' => ( is => 'ro' ) );
113 isa_ok( MyApp::User->meta, 'MyApp::Meta::Class' );
114 is( MyApp::User->meta->table, 'User',
115 'MyApp::User->meta->table returns User' );
116 ok( MyApp::User->can('username'),
117 'MyApp::User has username method' );