allow optional renaming of exported generator
[p5sagit/Package-Variant.git] / lib / Package / Variant.pm
index c99e24f..b0c2698 100644 (file)
@@ -21,8 +21,10 @@ sub import {
   };
   *{"${target}::import"} = sub {
     my $target = caller;
+    my (undef, %arg) = @_;
+    my $as = defined($arg{as}) ? $arg{as} : $last;
     no strict 'refs';
-    *{"${target}::${last}"} = sub {
+    *{"${target}::${as}"} = sub {
       $me->build_variant_of($variable, @_);
     };
   };
@@ -40,8 +42,14 @@ sub import {
 sub build_variant_of {
   my ($me, $variable, @args) = @_;
   my $variant_name = "${variable}::_Variant_".++$Variable{$variable}{anon};
-  my @to_import = keys %{$Variable{$variable}{args}{importing}||{}};
-  my $setup = join("\n", "package ${variant_name};", (map "use $_;", @to_import), "1;");
+  my $import = $Variable{$variable}{args}{importing} || {};
+  my $setup = join("\n",
+    "package ${variant_name};",
+    (map sprintf(
+      q!use %s @{$import->{'%s'}||[]};!, $_, quotemeta($_),
+    ), keys %$import),
+    "1;",
+  );
   eval $setup
     or die "evaling ${setup} failed: $@";
   my $subs = $Variable{$variable}{subs};
@@ -170,7 +178,8 @@ your package.
   use My::Variant;
   my $new_variant_package = Variant( @variant_arguments );
 
-The package is now fully initialized and used.
+The package is now fully initialized and used. You can import the
+subroutine under a different name by specifying an C<as> argument.
 
 =head2 Dynamic creation of variant packages
 
@@ -233,6 +242,19 @@ This method is provided for you. It will allow a user to C<use> your
 package and receive a subroutine taking C<@arguments> defining the variant
 and returning the name of the newly created variant package.
 
+The following options can be specified when importing:
+
+=over
+
+=item * B<as>
+
+  use Some::Variant::Package as => 'Foo';
+  my $variant_package = Foo( @arguments );
+
+Exports the generator subroutine under a different name than the default.
+
+=back
+
 =head1 C<Package::Variant> METHODS
 
 These methods are available on C<Package::Variant> itself.