Author: dylan
Date: 2005-01-04 00:27:01 -0500 (Tue, 04 Jan 2005)
New Revision: 518
Added:
trunk/main/core/t/config.t
Modified:
trunk/main/core/lib/Haver/Config.pm
Log:
We merge default now. There is even a simple config.t test.
Please write more tests, someone. :)
Modified: trunk/main/core/lib/Haver/Config.pm
===================================================================
--- trunk/main/core/lib/Haver/Config.pm 2005-01-04 05:05:23 UTC (rev 517)
+++ trunk/main/core/lib/Haver/Config.pm 2005-01-04 05:27:01 UTC (rev 518)
@@ -19,7 +19,11 @@
package Haver::Config;
use strict;
use warnings;
+
+use Haver::Preprocessor;
use base 'Haver::Base';
+use Scalar::Util 'reftype';
+use Carp;
use YAML ();
our $VERSION = 0.08;
@@ -42,10 +46,10 @@
if (-e $file) {
$config = YAML::LoadFile($file);
} else {
- $config = { %{ $me->{default} } };
+ $config = {};
}
-
- $me->{config} = $config;
+
+ $me->{config} = merge_hash($config, $me->{default});
}
sub save {
@@ -61,4 +65,50 @@
$me->{config};
}
+# Author: bdonlan
+sub merge_struct {
+ # ASSERT: @_ == 2;
+ my ($left, $right) = @_;
+ my $func = "merge_struct(\$left,\$right):";
+
+ unless (ref $left and ref $right) {
+ return $left;
+ }
+
+ if (reftype $left ne reftype $right) {
+ croak "$func \$left and \$right are not the same!";
+ }
+ if (reftype $left eq 'HASH') {
+ goto &merge_hash;
+ } elsif (reftype $left eq 'ARRAY') {
+ goto &merge_array;
+ } else {
+ croak "$func Can not merge a(n) ", reftype $left, " reference!";
+ }
+}
+
+# Author: bdonlan
+sub merge_hash {
+ # ASSERT: reftype($_[0]) eq 'HASH' and reftype($_[1]) eq 'HASH';
+ my ($left, $right) = @_;
+ my %merged = %$left;
+ for (keys %$right) {
+ if (exists $merged{$_}) {
+ $merged{$_} = merge_struct($merged{$_}, $right->{$_});
+ } else {
+ $merged{$_} = $right->{$_};
+ }
+ }
+ return \%merged;
+}
+
+# Author: bdonlan
+sub merge_array {
+ # ASSERT: reftype($_[0]) eq 'ARRAY' and reftype($_[1]) eq 'ARRAY';
+ my ($left, $right) = @_;
+ return [EMAIL PROTECTED], @$right];
+}
+
+
+
1;
Added: trunk/main/core/t/config.t
===================================================================
--- trunk/main/core/t/config.t 2005-01-04 05:05:23 UTC (rev 517)
+++ trunk/main/core/t/config.t 2005-01-04 05:27:01 UTC (rev 518)
@@ -0,0 +1,27 @@
+#!/usr/bin/perl
+# vim: set ft=perl:
+
+#########################
+
+# change 'tests => 1' to 'tests => last_test_to_print';
+
+use Test::More tests => 3;
+BEGIN {
+ use_ok('Haver::Config');
+};
+
+can_ok('Haver::Config', 'new', 'config');
+
+my $d =
+my $ch = new Haver::Config (
+ file => 'foobar',
+ default => {
+ stuff => {
+ monkeys => 2,
+ },
+ foo => 'bar',
+ },
+);
+my $c = $ch->config;
+
+is_deeply($c, { stuff => { monkeys => 2 }, foo => 'bar' }, "Config with
default values");