Skip to content

Instantly share code, notes, and snippets.

@akzhan
Created December 28, 2016 12:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akzhan/e0acff907e3b468db756749eb3be5e9a to your computer and use it in GitHub Desktop.
Save akzhan/e0acff907e3b468db756749eb3be5e9a to your computer and use it in GitHub Desktop.
BUX::Util::JSONColumn for DBIx::Class
package BUX::Util::JSONColumn;
use strict;
use warnings;
use utf8;
use JSON::XS ();
use Encode qw( encode_utf8 decode_utf8 );
sub register_column {
my $self = shift;
my ( $column, $info, $args ) = @_;
$self->next::method(@_);
return unless defined $info->{json};
my %modifiers = (
utf8 => 1,
);
%modifiers = ( %modifiers, %{$info->{json}} ) if ref $info->{json};
my $jsoner = JSON::XS->new;
for my $mod ( keys %modifiers ) {
my $args = $modifiers{$mod};
if ( ref($args) ne 'ARRAY' ) {
$args = [ $args ];
}
$jsoner = $jsoner->$mod( @{ $args } );
}
my $unfreezer = sub {
my $value = shift;
return undef unless defined $value;
$value = encode_utf8( $value );
return $jsoner->decode( $value );
};
my $freezer = sub {
my $value = shift;
return undef unless defined $value;
$value = $jsoner->encode( $value );
$value = decode_utf8( $value );
return $value;
};
$self->inflate_column(
$column => {
inflate => $unfreezer,
deflate => $freezer,
},
);
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment