Created
March 17, 2017 13:48
-
-
Save jhthorsen/a55c66ddbd2f2341beebd9c2687d0d7d 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
package Mojo::JSON::Patch; | |
use Mojo::Base 'Mojo::JSON::Pointer'; | |
use Carp 'croak'; | |
use Mojo::Path; | |
sub set { | |
my $self = shift; | |
my $path = Mojo::Path->new(shift); | |
my $val = shift; | |
croak 'Non-exising JSON node' unless $self->contains("$path"); | |
my $leaf = pop @$path; # TODO: Should this happen before or after contains() ? | |
my $parent = $self->get("$path"); | |
if (ref $parent eq 'ARRAY') { | |
$parent->[$leaf] = $val; | |
} | |
elsif (ref $parent eq 'HASH') { | |
$parent->{$leaf} = $val; | |
} | |
return $self; | |
} | |
package main; | |
use Test::More; | |
my $p = Mojo::JSON::Patch->new({foo => {bar => [24, 42]}}); | |
is $p->get('/foo/bar/0'), 24, 'get original value'; | |
is $p->set('/foo/bar/1', 54), $p, 'set new value'; | |
is $p->get('/foo/bar/1'), 54, 'get new value'; | |
eval { $p->set('/foo/bar/3', 54) }; | |
like $@, qr{Non-exising}, 'non exising'; | |
is $p->set('/foo/bar', [64]), $p, 'set /foo/bar'; | |
is $p->get('/foo/bar/0'), 64, 'get new array'; | |
done_testing; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment