aboutsummaryrefslogtreecommitdiffstats
path: root/lib/Youri/Utils.pm
blob: a1e55f883966e70189ea3b68b7f776b2d6a4c4a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# $Id$
package Youri::Utils;

=head1 NAME

Youri::Utils - Youri shared functions

=head1 DESCRIPTION

This module implement some helper functions for all youri applications.

=cut

use base qw(Exporter);
use Carp;
use strict;
use warnings;

our @EXPORT = qw(
    create_instance
    load
    add2hash
    add2hash_
);

=head2 create_instance(class => I<$class>, I<%options>)

Create an instance of a class at runtime.
I<$class> is the class name.
I<%options> are passed to the class constructor.
Returns the class instance.

=cut

sub create_instance {
    my ($expected_class, %options) = @_;

    die 'No expected class given' unless $expected_class;
    die "No class given, expected derivated class from '$expected_class'" unless $options{class};

    # extract class from options
    my $class = $options{class};
    delete $options{class};

    # ensure loaded
    load($class);

    # check interface
    die "$class is not a $expected_class" unless $class->isa($expected_class);

    # instantiate
    no strict 'refs';
    return $class->new(%options);
}

sub load {
    my ($class) = @_;

    $class .= '.pm';
    $class =~ s/::/\//g;
    require $class;
}

# structure helpers

sub add2hash  {
    my ($a, $b) = @_;
    while (my ($k, $v) = each %{$b || {}}) {
        $a->{$k} ||= $v;
    }
    return $a;
}

sub add2hash_ {
    my ($a, $b) = @_;
    while (my ($k, $v) = each %{$b || {}}) {
        exists $a->{$k} or $a->{$k} = $v;
    }
    return $a;
}

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2002-2006, YOURI project

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

=cut

1;