Search code examples
jsonperlmemcacheddancer

How do I tell my dancer app to serialize objects in its cache?


I'm using a CHI interface to memcached (or File in devel) in my Dancer app, but I'm getting an error in the serializer when I cache an object. I have the following in my dancer config:

engines:
  JSON:
    allow_blessed: 1
    convert_blessed: 1

What else do I need?

Error message:
Error while loading bin/app.pl: encountered object 'C3M::CMF=HASH(0x3ef8aa8)', but neither allow_blessed nor convert_blessed settings are enabled at /usr/lib/perl5/site_perl/5.10/CHI/Serializer/JSON.pm line 19.

Solution

  • CHI::Serializer::JSON doesn't use the same serializer as Dancer::Serializer::JSON. Dancer::Serializer::JSON uses setting('engines') in config.yml, but there's no way to send configuration options to CHI::Serializer::JSON.

    workaround:

    use CHI::Serializer::JSON; 
    my $JSON = JSON->new->utf8->canonical;
    $JSON->allow_blessed(1);
    $JSON->convert_blessed(1);
    *CHI::Serializer::JSON::serialize   = sub { $JSON->encode( $_[1] ) };
    *CHI::Serializer::JSON::deserialize = sub { $JSON->decode( $_[1] ) };