Skip to content

Instantly share code, notes, and snippets.

@tobyink
Created April 8, 2014 21:51
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tobyink/10198397 to your computer and use it in GitHub Desktop.
Save tobyink/10198397 to your computer and use it in GitHub Desktop.
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";
@jadeallenx
Copy link

Thanks!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment