1 package MooseX::Declare::Syntax::KeywordHandling;
4 use Moose::Util::TypeConstraints;
6 use Sub::Install qw( install_sub );
7 use Moose::Meta::Class ();
8 use List::MoreUtils qw( uniq );
10 use aliased 'MooseX::Declare::Context';
12 use namespace::clean -except => 'meta';
20 isa => subtype(as 'Str', where { /^ [_a-z] [_a-z0-9]* $/ix }),
24 sub get_identifier { shift->identifier }
26 sub context_class { Context }
28 sub context_traits { }
31 my ($self, $setup_class, %args) = @_;
33 # make sure the stack is valid
34 my $stack = $args{stack} || [];
35 my $ident = $self->get_identifier;
37 # setup the D:D handler for our keyword
38 Devel::Declare->setup_for($setup_class, {
40 const => sub { $self->parse_declaration((caller(1))[1], \%args, @_) },
44 # search or generate a real export
45 my $export = $self->can('generate_export') ? $self->generate_export($setup_class) : sub { };
52 }) unless $setup_class->can($ident);
57 sub parse_declaration {
58 my ($self, $caller_file, $args, @ctx_args) = @_;
60 # find and load context object class
61 my $ctx_class = $self->context_class;
62 Class::MOP::load_class $ctx_class;
65 if (my @ctx_traits = uniq $self->context_traits) {
67 Class::MOP::load_class $_
70 $ctx_class = Moose::Meta::Class->create_anon_class(
71 superclasses => [$ctx_class],
72 roles => [@ctx_traits],
77 # create a context object and initialize it
78 my $ctx = $ctx_class->new(
80 caller_file => $caller_file,
82 $ctx->init(@ctx_args);
84 # parse with current context
85 return $self->parse($ctx);
94 MooseX::Declare::Syntax::KeywordHandling - Basic keyword functionality
98 This role provides the functionality common for all keyword handlers
99 in L<MooseX::Declare>.
105 This is the name of the actual keyword. It is a required string that is in
106 the same format as a usual Perl identifier.
108 =head1 REQUIRED METHODS
112 Object->parse (Object $context)
114 This method must implement the actual parsing of the keyword syntax.
118 =head2 get_identifier
120 Str Object->get_identifier ()
122 Returns the name the handler will be setup under.
126 Object->setup_for (ClassName $class, %args)
128 This will setup the handler in the specified C<$class>. The handler will
129 dispatch to the L</parse_declaration> method when the keyword is used.
131 A normal code reference will also be exported into the calling namespace.
132 It will either be empty or, if a C<generate_export> method is provided,
133 the return value of that method.
135 =head2 parse_declaration
137 Object->parse_declaration (Str $filename, HashRef $setup_args, @call_args)
139 This simply creates a new L<context|MooseX::Declare::Context> and passes it
140 to the L</parse> method.
146 =item * L<MooseX::Declare>
148 =item * L<MooseX::Declare::Context>
152 =head1 AUTHOR, COPYRIGHT & LICENSE
154 See L<MooseX::Declare>