added merge_config_hashes convenience method
Brian Cassidy [Wed, 31 May 2006 13:59:49 +0000 (13:59 +0000)]
Changes
lib/Catalyst/Component.pm

diff --git a/Changes b/Changes
index 233fadb..ff419a4 100644 (file)
--- a/Changes
+++ b/Changes
@@ -1,5 +1,6 @@
 This file documents the revision history for Perl extension Catalyst.
 
+        - added merge_config_hashes() as a convenience method
         - Swapped out CGI::Cookie in favour of CGI::Simple::Cookie
         - Removed test dependencies on Test::NoWarnings, Test::MockObject
         - Removed dependency on UNIVERSAL::require
index 4b12fda..b38361e 100644 (file)
@@ -62,7 +62,7 @@ sub new {
     # Temporary fix, some components does not pass context to constructor
     my $arguments = ( ref( $_[-1] ) eq 'HASH' ) ? $_[-1] : {};
 
-    return $self->NEXT::new( { %{ $self->config }, %{$arguments} } );
+    return $self->NEXT::new( $self->merge_config_hashes( $self->config, $arguments ) );
 }
 
 =head2 COMPONENT($c, $arguments)
@@ -92,7 +92,7 @@ sub COMPONENT {
         }
         else {
             my $class = ref $self || $self;
-            my $new = { %{ $self->config }, %{$arguments} };
+            my $new   = $self->merge_config_hashes( $self->config, $arguments );
             return bless $new, $class;
         }
     }
@@ -116,8 +116,10 @@ sub config {
         $self->_config( $config = {} );
     }
     if (@_) {
-        $config = { %{$config}, %{@_ > 1 ? {@_} : $_[0]} };
-        $self->_config($config);
+        my $newconfig = { %{@_ > 1 ? {@_} : $_[0]} };
+        $self->_config(
+            $self->merge_config_hashes( $config, $newconfig )
+        );
     }
     return $config;
 }
@@ -132,6 +134,32 @@ sub process {
           . " did not override Catalyst::Component::process" );
 }
 
+=head2 $c->merge_hash_config( $hashref, $hashref )
+
+Merges two hashes together recursively, giving right-hand precedence.
+
+=cut
+
+sub merge_config_hashes {
+    my ( $self, $lefthash, $righthash ) = @_;
+
+    my %merged = %$lefthash;
+    for my $key ( keys %$righthash ) {\r
+        my $right_ref = ( ref $righthash->{ $key } || '' ) eq 'HASH';\r
+        my $left_ref  = ( ( exists $lefthash->{ $key } && ref $lefthash->{ $key } ) || '' ) eq 'HASH';\r
+        if( $right_ref and $left_ref ) {\r
+            $merged{ $key } = $self->merge_config_hashes(
+                $lefthash->{ $key }, $righthash->{ $key }
+            );\r
+        }
+        else {
+            $merged{ $key } = $righthash->{ $key };
+        }\r
+    }
+    
+    return \%merged;
+}
+
 =head1 OPTIONAL METHODS
 
 =head2 ACCEPT_CONTEXT($c, @args)