4b1113f9a2bba07720ad48527bc34852fa52b15d
[p5sagit/Import-Into.git] / lib / Import / Into.pm
1 package Import::Into;
2
3 use strict;
4 use warnings FATAL => 'all';
5
6 our $VERSION = '1.002001'; # 1.2.1
7
8 sub _prelude {
9   my $target = shift;
10   my ($package, $file, $line, $level)
11     = ref $target         ? @{$target}{qw(package filename line)}
12     : $target =~ /[^0-9]/ ? ($target)
13                           : (undef, undef, undef, $target);
14   if (defined $level) {
15     my ($p, $fn, $ln) = caller($level + 2);
16     $package ||= $p;
17     $file    ||= $fn;
18     $line    ||= $ln;
19   }
20   qq{package $package;\n}
21     . ($file ? "#line $line \"$file\"\n" : '')
22 }
23
24 sub _make_action {
25   my ($action, $target) = @_;
26   my $version = ref $target && $target->{version};
27   my $ver_check = $version ? '$_[0]->VERSION($version);' : '';
28   eval _prelude($target).qq{sub { $ver_check shift->$action(\@_) }}
29     or die "Failed to build action sub to ${action} for ${target}: $@";
30 }
31
32 sub import::into {
33   my ($class, $target, @args) = @_;
34   _make_action(import => $target)->($class, @args);
35 }
36
37 sub unimport::out_of {
38   my ($class, $target, @args) = @_;
39   _make_action(unimport => $target)->($class, @args);
40 }
41
42 1;
43
44 __END__
45
46 =head1 NAME
47
48 Import::Into - import packages into other packages
49
50 =head1 SYNOPSIS
51
52   package My::MultiExporter;
53
54   use Import::Into;
55
56   use Thing1 ();
57   use Thing2 ();
58
59   # simple
60   sub import {
61     Thing1->import::into(scalar caller);
62   }
63
64   # multiple
65   sub import {
66     my $target = caller;
67     Thing1->import::into($target);
68     Thing2->import::into($target, qw(import arguments));
69   }
70
71   # by level
72   sub import {
73     Thing1->import::into(1);
74   }
75
76   # with exporter
77   use base qw(Exporter);
78   sub import {
79     shift->export_to_level(1);
80     Thing1->import::into(1);
81   }
82
83   # no My::MultiExporter == no Thing1
84   sub unimport {
85     Thing1->unimport::out_of(scalar caller);
86   }
87
88 People wanting to re-export your module should also be using L<Import::Into>.
89 Any exporter or pragma will work seamlessly.
90
91 Note: You do B<not> need to make any changes to Thing1 to be able to call
92 C<import::into> on it. This is a global method, and is callable on any
93 package (and in fact on any object as well, although it's rarer that you'd
94 want to do that).
95
96 =head1 DESCRIPTION
97
98 Writing exporters is a pain. Some use L<Exporter>, some use L<Sub::Exporter>,
99 some use L<Moose::Exporter>, some use L<Exporter::Declare> ... and some things
100 are pragmas.
101
102 Exporting on someone else's behalf is harder.  The exporters don't provide a
103 consistent API for this, and pragmas need to have their import method called
104 directly, since they effect the current unit of compilation.
105
106 C<Import::Into> provides global methods to make this painless.
107
108 =head1 METHODS
109
110 =head2 $package->import::into( $target, @arguments );
111
112 A global method, callable on any package.  Imports the given package into
113 C<$target>.  C<@arguments> are passed along to the package's import method.
114
115 C<$target> can be an package name to export to, an integer for the
116 caller level to export to, or a hashref with the following options:
117
118 =over 4
119
120 =item package
121
122 The target package to export to.
123
124 =item filename
125
126 The apparent filename to export to.  Some exporting modules, such as
127 L<autodie> or L<strictures>, care about the filename they are being imported
128 to.
129
130 =item line
131
132 The apparent line number to export to.  To be combined with the C<filename>
133 option.
134
135 =item level
136
137 The caller level to export to.  This will automatically populate the
138 C<package>, C<filename>, and C<line> options, making it the easiest most
139 constent option.
140
141 =item version
142
143 A version number to check for the module.  The equivalent of specifying the
144 version number on a C<use> line.
145
146 =back
147
148 =head2 $package->unimport::out_of( $target, @arguments );
149
150 Equivalent to C<import::into>, but dispatches to C<$package>'s C<unimport>
151 method instead of C<import>.
152
153 =head1 WHY USE THIS MODULE
154
155 The APIs for exporting modules aren't consistent.  L<Exporter> subclasses
156 provide export_to_level, but if they overrode their import method all bets
157 are off.  L<Sub::Exporter> provides an into parameter but figuring out
158 something used it isn't trivial. Pragmas need to have their C<import> method
159 called directly since they affect the current unit of compilation.
160
161 It's ... annoying.
162
163 However, there is an approach that actually works for all of these types.
164
165   eval "package $target; use $thing;"
166
167 will work for anything checking caller, which is everything except pragmas.
168 But it doesn't work for pragmas - pragmas need:
169
170   $thing->import;
171
172 because they're designed to affect the code currently being compiled - so
173 within an eval, that's the scope of the eval itself, not the module that
174 just C<use>d you - so
175
176   sub import {
177     eval "use strict;"
178   }
179
180 doesn't do what you wanted, but
181
182   sub import {
183     strict->import;
184   }
185
186 will apply L<strict> to the calling file correctly.
187
188 Of course, now you have two new problems - first, that you still need to
189 know if something's a pragma, and second that you can't use either of
190 these approaches alone on something like L<Moose> or L<Moo> that's both
191 an exporter and a pragma.
192
193 So, a solution for that is:
194
195   my $sub = eval "package $target; sub { shift->import(\@_) }";
196   $sub->($thing, @import_args);
197
198 which means that import is called from the right place for pragmas to take
199 effect, and from the right package for caller checking to work - and so
200 behaves correctly for all types of exporter, for pragmas, and for hybrids.
201
202 Additionally, some import routines check the filename they are being imported
203 to.  This can be dealt with by generating a L<#line directive|perlsyn/Plain
204 Old Comments (Not!)> in the eval, which will change what C<caller> reports for
205 the filename when called in the importer. The filename and line number to use
206 in the directive then need to be fetched using C<caller>:
207
208   my ($target, $file, $line) = caller(1);
209   my $sub = eval qq{
210     package $target;
211   #line $line "$file"
212     sub { shift->import(\@_) }
213   };
214   $sub->($thing, @import_args);
215
216 And you need to switch between these implementations depending on if you are
217 targeting a specific package, or something in your call stack.
218
219 Remembering all this, however, is excessively irritating. So I wrote a module
220 so I didn't have to anymore. Loading L<Import::Into> creates a global method
221 C<import::into> which you can call on any package to import it into another
222 package. So now you can simply write:
223
224   use Import::Into;
225
226   $thing->import::into($target, @import_args);
227
228 This works because of how perl resolves method calls - a call to a simple
229 method name is resolved against the package of the class or object, so
230
231   $thing->method_name(@args);
232
233 is roughly equivalent to:
234
235   my $code_ref = $thing->can('method_name');
236   $code_ref->($thing, @args);
237
238 while if a C<::> is found, the lookup is made relative to the package name
239 (i.e. everything before the last C<::>) so
240
241   $thing->Package::Name::method_name(@args);
242
243 is roughly equivalent to:
244
245   my $code_ref = Package::Name->can('method_name');
246   $code_ref->($thing, @args);
247
248 So since L<Import::Into> defines a method C<into> in package C<import>
249 the syntax reliably calls that.
250
251 For more craziness of this order, have a look at the article I wrote at
252 L<http://shadow.cat/blog/matt-s-trout/madness-with-methods> which covers
253 coderef abuse and the C<${\...}> syntax.
254
255 Final note: You do still need to ensure that you already loaded C<$thing> - if
256 you're receiving this from a parameter, I recommend using L<Module::Runtime>:
257
258   use Import::Into;
259   use Module::Runtime qw(use_module);
260
261   use_module($thing)->import::into($target, @import_args);
262
263 And that's it.
264
265 =head1 SEE ALSO
266
267 I gave a lightning talk on this module (and L<curry> and L<Safe::Isa>) at
268 L<YAPC::NA 2013|https://www.youtube.com/watch?v=wFXWV2yY7gE&t=46m05s>.
269
270 =head1 ACKNOWLEDGEMENTS
271
272 Thanks to Getty for asking "how can I get C<< use strict; use warnings; >>
273 turned on for all consumers of my code?" and then "why is this not a
274 module?!".
275
276 =head1 AUTHOR
277
278 mst - Matt S. Trout (cpan:MSTROUT) <mst@shadowcat.co.uk>
279
280 =head1 CONTRIBUTORS
281
282 haarg - Graham Knop (cpan:HAARG) <haarg@haarg.org>
283
284 =head1 COPYRIGHT
285
286 Copyright (c) 2012 the Import::Into L</AUTHOR> and L</CONTRIBUTORS>
287 as listed above.
288
289 =head1 LICENSE
290
291 This library is free software and may be distributed under the same terms
292 as perl itself.
293
294 =cut