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 <jstephenson@mvlc.org>
Signed-off-by: Ben Shum <bshum@biblio.org>
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 {
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] );