From b9edf30f9f2e5bcda86c4724496e6261b64148a0 Mon Sep 17 00:00:00 2001 From: Jason Stephenson Date: Thu, 26 Sep 2013 01:53:35 -0400 Subject: [PATCH] LP1223903 - Add from_bare_hash to Fieldmapper.pm. Teach the Perl Fieldmapper.pm to build objects from a hashref in a similar manner to how the JS Fieldmapper already can. You might use it if you retrieved a database row as a hashref, like so: my $hashref = {}; my $class = Fieldmapper::class_for_hint('bre'); my $bre = $class->from_bare_hash($hashref); We also modify the Fieldmapper's properties method to sort the array of field names it returns by position. This makes the return value a lot more useful for on the fly object construction and other fancy tricks. Signed-off-by: Jason Stephenson Signed-off-by: Ben Shum --- Open-ILS/src/perlmods/lib/OpenILS/Utils/Fieldmapper.pm | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/Open-ILS/src/perlmods/lib/OpenILS/Utils/Fieldmapper.pm b/Open-ILS/src/perlmods/lib/OpenILS/Utils/Fieldmapper.pm index f8bc724523..749f9b99ab 100644 --- a/Open-ILS/src/perlmods/lib/OpenILS/Utils/Fieldmapper.pm +++ b/Open-ILS/src/perlmods/lib/OpenILS/Utils/Fieldmapper.pm @@ -424,7 +424,8 @@ sub has_field { sub properties { my $self = shift; my $class_name = $self->class_name; - return keys %{$$fieldmap{$class_name}{fields}}; + my $fields = $$fieldmap{$class_name}{fields}; + return sort {$$fields{$a}{position} <=> $$fields{$b}{position}} keys %{$fields}; } sub to_bare_hash { @@ -439,6 +440,19 @@ sub to_bare_hash { return \%hash; } +# To complement to_bare_hash, and to mimic the fromHash method of the +# JavaScript Fieldmapper, from_bare_hash takes a hashref argument and +# builds an object from that. +sub from_bare_hash { + my $self = shift; + my $hash = shift; + my @value = (); + for my $f ($self->properties) { + push @value, $$hash{$f}; + } + return $self->new(\@value); +} + sub clone { my $self = shift; return $self->new( [@$self] ); -- 2.11.0