I've been trying to find a Perl module that converts a YAML file into moose objects without having to pre-declare the structure as you seem to need to do when using MooseX::YAML. Does anyone know of such a module (or script)?
Don't.
Moose classes, their attributes, and whatever else belongs to them, have a lot of meta-data attached to them. You can't infer all of that meta-data from the data of a single instance.
I'm assuming, given a yaml document as
---
foo: 42
bar: ['moo', 'kooh']
you'd expect and object back that responds to calls to a foo
and a bar
method, returning the respective values. But how should those accessors behave? Should they be simple reader-methods, or also allow writing? Should they validate against any kind of typeconstraint? etc.
If all you really need is something that makes some unblessed data-structure accessible like an object, have a look at Data::Hive
, Hash::AsObject
, and similar modules instead.
If you really want to build proper Moose classes, and are either alright with the guesswork that'd be involved, or happen to have the necessary meta-data available somewhere, you can just use the meta-protocol.
my $class = Moose::Meta::Class->create_anon_class(
attributes => [map {
# your particular set of assumptions here
Moose::Meta::Attribute->new($_ => (is => 'ro', ...))
} keys %{ $deserialized_yaml }],
);
my $instance = $class->name->new($deserialized_yaml);
$instance->$some_key_in_the_yaml_document;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With