-
-
Save jadeallenx/10340468 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use strict; | |
use warnings; | |
{ | |
package JSON::ObjectFactory; | |
use Carp; | |
use Class::Tiny { json => sub { 'JSON::PP'->new } }; | |
use Import::Into; | |
use JSON::PP (); | |
sub decode { | |
my $self = shift; | |
my $hash = $self->json->decode($_[0]); | |
ref($hash) eq 'HASH' | |
or croak("JSON did not decode to a hashref"); | |
return $self->_from_hashref($hash); | |
} | |
sub _from_hashref { | |
my $self = shift; | |
my ($hash) = @_; | |
my $classname = $self->_mk_class($hash); | |
return $classname->new($hash); | |
} | |
sub _mk_class { | |
my $self = shift; | |
my ($hash) = @_; | |
my @attrs = | |
grep !/\A(new|can|isa|DOES|VERSION|DESTROY|BUILD(ARGS)?|DEMOLISH)\z/, | |
grep /\A[^\W0-9]\w*\z/, | |
sort keys %$hash; | |
my $class = sprintf( | |
'%s::__CLASS_WITH_ATTRIBUTES__::%s', | |
ref($self), | |
join("::", @attrs), | |
); | |
'Class::Tiny'->import::into($class, @attrs); | |
return $class; | |
} | |
} | |
my $factory = 'JSON::ObjectFactory'->new; | |
my $obj = $factory->decode(q( { "foo": 1, "bar": 2, "_baz": 3 } )); | |
print $obj->foo, "\n"; | |
print $obj->bar, "\n"; | |
print $obj->_baz, "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment