Author: spadkins
Date: Fri Jun 18 17:13:28 2010
New Revision: 14169

Modified:
   p5ee/trunk/App-Repository/lib/App/RepositoryObject.pm

Log:
added TO_JSON() method that helps with serializing RepositoryObjects to JSON 
(as required by the JSON module)

Modified: p5ee/trunk/App-Repository/lib/App/RepositoryObject.pm
==============================================================================
--- p5ee/trunk/App-Repository/lib/App/RepositoryObject.pm       (original)
+++ p5ee/trunk/App-Repository/lib/App/RepositoryObject.pm       Fri Jun 18 
17:13:28 2010
@@ -8,6 +8,7 @@
 
 use App;
 use App::Repository;
+use Scalar::Util qw(looks_like_number);
 
 use strict;
 
@@ -187,6 +188,46 @@
 }
 
 #############################################################################
+# TO_JSON()
+#############################################################################
+
+=head2 TO_JSON()
+
+    * Signature: $obj->TO_JSON();
+    * Throws:    App::Exception
+    * Since:     0.01
+
+    Sample Usage: 
+
+    $json_text = $obj->TO_JSON();
+
+Converts the RepositoryObject to serialized JSON text. This method is used by 
the JSON module.
+
+=cut
+
+sub TO_JSON {
+    my ($self) = @_;
+    my ($json, @keys_values, $value);
+    foreach my $key (sort keys %$self) {
+        $value = $self->{$key};
+        if (!defined $value) {
+            push(@keys_values, "'$key' : null");
+        }
+        elsif ($key eq "_repository") {
+            push(@keys_values, "'$key' : '$value->{name}'");
+        }
+        elsif (looks_like_number($value)) {
+            push(@keys_values, "'$key' : $value");
+        }
+        else {
+            push(@keys_values, "'$key' : '$value'");
+        }
+    }
+    $json = "{" . join(", ", @keys_values) . "}";
+    return($json);
+}
+
+#############################################################################
 # PRIVATE METHODS
 #############################################################################
 

Reply via email to