I'm writing a module for a moose object. I would like to allow a user using this object (or myself...) add some fields on the fly as he/she desires. I can't define these fields a priori since I simply don't know what they will be.
I currently simply added a single field called extra of type hashref which is is set to rw
, so users can simply put stuff in that hash:
# $obj is a ref to my Moose object
$obj->extra()->{new_thingie}="abc123"; # adds some arbitrary stuff to the object
say $obj->extra()->{new_thingie};
This works. But... is this a common practice? Any other (possibly more elegant) ideas?
Note I do not wish to create another module the extends this one, this really just for on-the-fly stuff I'd like to add.
If you haven't made the class immutable (there is a performance penalty for not doing that, in addition to my concerns about changing class definitions on the fly), you should be able to do that by getting the meta class for the object (using
$meta = $object->meta
) and using theadd_attribute
method in Class::MOP::Class.Output:
Just in case you want to add a method to an object and not to the whole class then have a look at something like
MooseX::SingletonMethod
.E.g.
So in above the method
baz
is only added to the object$foo
and not to classFoo
.Hmmm... I wonder if I could implement a MooseX::SingletonAttribute?
Some previous SO answer using
MooseX::SingletonMethod
:And also this blog post maybe of use and/or interest: Easy Anonymous Objects
/I3az/
Even if it's not a good pratice to modify a class at runtime, you can simply make the meta-class mutable, add the attribute(s) and make class immutable again:
I would probably do this via native traits:
On an object you'd use this like the following:
A common use-case for stuff like this is adding optional introspectable data to exception and message classes.