From: Matt S Trout Date: Wed, 11 Dec 2013 01:56:28 +0000 (+0000) Subject: Add a constructor that accepts arguments X-Git-Tag: v1.001000~2 X-Git-Url: http://git.shadowcat.co.uk/gitweb/gitweb.cgi?a=commitdiff_plain;h=939f9a29d82fd0bc8ec3375e9567f5e70b56dcf0;p=p5sagit%2FJSON-MaybeXS.git Add a constructor that accepts arguments --- diff --git a/Changes b/Changes index d5344bd..ba09ca3 100644 --- a/Changes +++ b/Changes @@ -1,2 +1,4 @@ + - Add a constructor for people who want to forget how silly the JSON API is + 1.000000 - 2013-05-22 - Released on an unsuspecting world. diff --git a/lib/JSON/MaybeXS.pm b/lib/JSON/MaybeXS.pm index 9f740ad..68d84b7 100644 --- a/lib/JSON/MaybeXS.pm +++ b/lib/JSON/MaybeXS.pm @@ -31,6 +31,14 @@ our @EXPORT = qw(encode_json decode_json JSON); sub JSON () { our $JSON_Class } +sub new { + shift; + my %args = @_ == 1 ? %{$_[0]} : @_; + my $new = (our $JSON_Class)->new; + $new->$_($args{$_}) for keys %args; + return $new; +} + 1; =head1 NAME @@ -47,6 +55,8 @@ JSON::MaybeXS - use L with a fallback to L my $json = JSON->new; + my $json_with_args = JSON::MaybeXS->new(utf8 => 1); # or { utf8 => 1 } + =head1 DESCRIPTION This module tries to load L, and if that fails instead @@ -57,6 +67,10 @@ It then exports the C and C functions from the loaded module, along with a C constant that returns the class name for calling C on. +If you're writing fresh code rather than replacing JSON.pm usage, you might +want to pass options as constructor args rather than calling mutators, so +we provide our own C method that supports that. + =head1 EXPORTS All of C, C and C are exported by default. @@ -92,6 +106,22 @@ and that object can then be used normally: my $data_structure = $json_obj->decode($json_text); # etc. +=head1 CONSTRUCTOR + +=head2 new + +With L and L you are required to call mutators +to set options, i.e. + + my $json = $class->new->utf8(1)->pretty(1); + +Since this is a trifle irritating and noticeably un-perlish, we also offer: + + my $json = JSON::MaybeXS->new(utf8 => 1, pretty => 1); + +which works equivalently to the above (and in the usual tradition will accept +a hashref instead of a hash, should you so desire). + =head1 AUTHOR mst - Matt S. Trout (cpan:MSTROUT)