http://qs321.pair.com?node_id=11146259


in reply to Framework for making Moose-compatible object from json

If you mean that you have Moose classes/roles available and you want to detect incoming objects in your JSON and call  ->new on the appropriate class, maybe also calling apply_all_roles to customize the object a bit, then you can do that using the JSON module's filter_json_object feature.

On the other hand, if you mean that you want to create a brand new Moose class with one attribute for each of the keys seen in the incoming hash, and a metaclass that enumerates these attributes, you have a harder problem. The hard part of the problem isn't creating the Moose class; the hard part is that once you create a Moose class it remains in memory for the duration of the program, because classes are global. You would want to at least recognize when the set of attributes was the same as a previous class and re-use that class. But, a malicious client could connect to your service requesting infinite different attributes, and run you out of memory. A possible solution here would be to create the class with a DESTROY method that deletes the entire class when the one-and-only instance of that class goes out of scope.

An additional problem is that some names are reserved by Perl or Moose. So if an object came in looking like

{ new => 1, meta => 2, BUILDARGS => 3, DESTROY => 4 }
blindly creating attribute accessors for it would be bad. I think you could still access the attributes using the MOP, as long as you didn't create accessors.

So if you only access the attributes using the MOP, then you might actually have a path forward, because you could make a subclass of the MOP classes which return dynamic info about the instance instead of static info about the class. Then you only need one Moose class, and it generates dynamic MOP on demand when you call  ->meta.

Then, the final thing you need to ask yourself is whether all of this is actually solving your problem, or just creating more work :-)