ClassLoader.pm 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # ------------------------------------------------------------------------------
  2. # (C) Crown copyright Met Office. All rights reserved.
  3. # For further details please refer to the file COPYRIGHT.txt
  4. # which you should have received as part of this distribution.
  5. # ------------------------------------------------------------------------------
  6. use strict;
  7. use warnings;
  8. package Fcm::Util::ClassLoader;
  9. use base qw{Exporter};
  10. our @EXPORT_OK = qw{load};
  11. use Carp qw{croak};
  12. use Fcm::Exception;
  13. sub load {
  14. my ($class, $test_method) = @_;
  15. if (!$test_method) {
  16. $test_method = 'new';
  17. }
  18. if (!UNIVERSAL::can($class, $test_method)) {
  19. eval('require ' . $class);
  20. if ($@) {
  21. croak(Fcm::Exception->new({message => sprintf(
  22. "%s: class loading failed: %s", $class, $@,
  23. )}));
  24. }
  25. }
  26. return $class;
  27. }
  28. 1;
  29. __END__
  30. =head1 NAME
  31. Fcm::ClassLoader
  32. =head1 SYNOPSIS
  33. use Fcm::Util::ClassLoader;
  34. $load_ok = Fcm::Util::ClassLoader::load($class);
  35. =head1 DESCRIPTION
  36. A wrapper for loading a class dynamically.
  37. =head1 FUNCTIONS
  38. =over 4
  39. =item load($class,$test_method)
  40. If $class can call $test_method, returns $class. Otherwise, attempts to
  41. require() $class and returns it. If this fails, croak() with a
  42. L<Fcm::Exception|Fcm::Exception>.
  43. =item load($class)
  44. Shorthand for C<load($class, 'new')>.
  45. =back
  46. =head1 DIAGNOSTICS
  47. =over 4
  48. =item L<Fcm::Exception|Fcm::Exception>
  49. The load($class,$test_method) function croak() with this exception if it fails
  50. to load the specified class.
  51. =back
  52. =head1 COPYRIGHT
  53. E<169> Crown copyright Met Office. All rights reserved.
  54. =cut