Re: BUILD and how to create a subclass object when creating a parent
I'm not sure you mean by create a subclass instance on creation of its superclass. Are you intending to have the superclass object have an attribute that holds an instance of the subclass? Perhaps can you show a diagram of what you intend your data to look like after construction is complete? On Mon, Apr 23, 2018 at 7:53 AM, Arjan Widlak - United Knowledge < ar...@unitedknowledge.nl> wrote: > Hi, > > I tried to use the BUILD method to create an instance of a subclass on > creating an instance of the parent. This does not work and the > documentation clearly explains why: > > http://search.cpan.org/dist/Moose/lib/Moose/Manual/Construct > ion.pod#BUILD_and_parent_classes > > BUILD methods are called from parent to child and hence this triggers a > loop. > > I am able to do this with the around method modifier, however I need to > override the behaviour in the subclass. This is also seems error prone and > bad practice. > > But if this cannot be done this way, how should it be done? How can I > always create a subclass instance on creation of it's superclass? > > Kind regards, > > Arjan >
Re: Annoying warning in Moose::Meta::Attribute; our $VERSION = '2.1604'
Can you possibly provide a bit of code that, when run, reproduces this warning? The 'package' key should normally exist with a defined value. many thanks! On Mon, Jan 18, 2016 at 10:25 AM,wrote: > Hi, > > I see the following when calling $self->meta->add_attribute in my code > under perl 5.10.1: > > Use of uninitialized value in string eq at > .../perl-5.10.1/lib/site_perl/5.10.1/x86_64-linux/Moose/Meta/Attribute.pm > line 1035. > > I think the following code segment: > > if ( > $method > && !$method->is_stub > && !$method->isa('Class::MOP::Method::Accessor') > && ( !$self->definition_context > || $method->package_name eq $self->definition_context->{package} ) > ) { > > > should look like: > > > if ( > $method > && !$method->is_stub > && !$method->isa('Class::MOP::Method::Accessor') > && ( !$self->definition_context > || exists(self->definition_context->{package}) && $method->package_name > eq $self->definition_context->{package} ) > ) { > > -- > Yuri > > >
Re: 'around' method modifier does not seem to work
On Sat, Aug 8, 2015 at 1:18 PM, Marcos Barbeitos msbarbei...@gmail.com wrote: I get it to work. Not a very elegant solution, for I must access the attribute directly instead of using an accessor. No, instead of return $self-{sequence}; you should do return $self-$orig(); to use the proper reader mechanism. One issue still remains though, if I pass the argument to the constructor: my $collection = DCSE::Collection-new ( id = 'test' , sequence = $sequence , helix = $dcse-helix ); I believe that 'around' is not called, for I get the unparsed argument when I fetch the attribute. This should be fixed when you fix the code path for the reader as above.
Re: 'around' method modifier does not seem to work
On Thu, Aug 6, 2015 at 4:04 PM, Marcos Barbeitos msbarbei...@gmail.com wrote: around 'sequence' = sub { my $orig = shift; my $self = shift; my $sequence = uc shift; # Do lots of things with $sequence and then return $self-$orig( $sequence ); } With no success, as expected. However, if I do: around 'sequence' = sub { my $orig = shift; my $self = shift; return $self-$orig( @_ ); } The attribute is set and life goes on. Of course, that does not work for me because I need to do a bunch of things to the argument passed to this method. The only difference I see between these two subs is the argument passed to $orig. So, have you tried printing it to check that it is what you expect it to be?
Re: PerlMagick and Moo
My question is how can you delete all the images but retain the Graphics::Magick object? I do not want to use the undef loop above. With normal perlmagick, you would say @$image = (); It's still just Perl -- how you got the image object is irrelevant. It's still a reference and you can operate on it as normal: my $image = $self-image; @$image = (); However, I'm shocked that there isn't an API for this. Operating on the reference directly is pretty gross. On Mon, Jul 20, 2015 at 8:35 AM, Rick Leir richard.l...@canadiana.ca wrote: Hi everyone, I have been working on a web service for GM PerlMagick, and Moo was suggested. The GM object is kept across requests, but the image memory is freed (question below). Here is what it looks like: package Something::Magick; use Graphics::Magick; use Dancer::Core::Types; # brings helper for types use MooX::Types::MooseLike::Base; # InstanceOf use MooX::Types::MooseLike; # Moo def must follow other defs. use Moo; with 'MooX::Singleton'; has image = ( is = 'rw', isa = InstanceOf['Graphics::Magick'], lazy = 1, builder = '_build_image' ); # The lazy attribute says to Moo that this attribute will be built (initialized) # only when called the first time. It means that the connection to GmImage won't be opened until necessary. sub _build_image { my ($self) = @_; Graphics::Magick-new( ); } sub BUILD { my ($self) = @_; $self-image( Graphics::Magick-new( )); } sub do_sequence { my $self = shift; my @seq = shift || 1; my $Arrayofhashes = \$seq[0][0]; my $sizeminus1 = @$$Arrayofhashes - 1; #++ 3 for my $i ( 0 .. $sizeminus1 ) { my $href = $seq[0][0][$i]; my $opname; my $filepath; my $gmparms; while( my ($k, $v) = each %$href ) { sanitize input .. if( $k eq 'op') { $opname = $v; } elsif( $k eq 'file') { $v =~ s/^\/+//; # remove any leading / $filepath = $v; } elsif( $k eq 'parms') { $gmparms = $v; } } .. if( $opname eq 'Read') { my $status = $self-image-Read( $absolute); warn $status if $status; } elsif( $opname eq 'Write') { my $status = $self-image-Write( $absolute); warn $status if $status; } ... # some op other than read,write # invoke it my $status = $self-image-$opname( $gmparms); warn $status if $status; } # delete all the images but retain the Graphics::Magick object # @$image = (); no # @self-image = (); no # @{self-image} = (); no my $i = 0; #while (defined ($self-image-[$i])) { while ( $i 10) { if (defined ($self-image-[$i])) { undef ($self-image-[$i]); print undef $i\n; } $i++; } } My question is how can you delete all the images but retain the Graphics::Magick object? I do not want to use the undef loop above. With normal perlmagick, you would say @$image = (); ( http://www.graphicsmagick.org/perl.html ) Should I learn more about Perl XS? TIA -- Rick
Re: overlapping attributes not detected
On Sat, Oct 04, 2014 at 08:02:05PM +, John Macdonald wrote: I'd rather see it as has '-XXX' to override, has '+XXX' to augment, and has 'XXX' to create a new attribute, with an error if an unsigned creation had a conflict. That provides the feature when it is desired without providing an action ata distance bug when it is unexpected. Perhaps, but it's far too late to make that change now without breaking everyone's code :)
Re: forced coercion
On Thu, Aug 21, 2014 at 09:23:00PM +, John Macdonald wrote: So, how do I specify a type that starts with a base type, but then applies a coercion? All the examples I see of coercions have a natural base encoding, with the coercion providing a way to take some other type of value and turn it into the base - but when base is a validated string, it is hard to get it to actually use the coercion. Right, coercions are only applied if the data doesn't already validate against the type. So (saying this without puzzling through your lookahead assertion) you may need to define your new type as a totally separate type on its own, not derived from the first type, so it doesn't already validate, and therefore executes the coercion.
Re: coerce a sub-subtype
On Mon, Jun 16, 2014 at 07:41:29PM +, John Macdonald wrote: In general, though, having a way of inheriting subtypes could be potentially a big saving in this sort of case. This would be a really nice feature to have in MooseX::Types - no one's made this happen yet though, sadly. (Patches welcome!) :) Also, Types::Tiny does have an option to support this already. I'd strongly suggest avoiding declaring named types using Moose::Util::TypeConstraints though, because such types are global (as are their coercions), which can cause nasty action-at-a-distance errors. You can get around this problem by declaring types only as local lexicals, e.g: my $type = subtype as ...;
Re: Parameterized Type Intersections?
I think you're suggesting being able to do appropos of: isa = Password[ length = 6, matches = qr { }, callback = sub { } ] I know this exists, which might help in implementing that: https://metacpan.org/pod/MooseX::Meta::TypeConstraint::Intersection Yep, and also MooseX::Types::Structured which lets you create data-dictionary-like types. Remember also that you can manually create any types you like by writing a custom verification sub: my $custom_type = subtype, from HashRef, where { custom sub here };
Re: Possible mis-use of Moose API or problem with coerce attribute check
On Fri, Mar 21, 2014 at 12:07:48PM +, Richard Harris wrote: subtype 'A', as 'Str', where { $_ eq 'foo' }; subtype 'B', as 'Str', where { $_ =~ /some regex/ }; subtype 'C', as 'Str', where { $_ =~ /different regex/ }; subtype 'Foo', as 'A|B|C', message { 'Invalid Foo' }; has foo = (is = 'rw', isa = 'Foo', required = 1, coerce = 1); The warning is: You can't coerce an attribute (foo) unless its type (Foo) has a coercion, Am I using the API wrong here? If so, what would be a better way to do this? Is a workaround available or is there a bug? The warning seems pretty clear to me -- you've declared an attribute with coerce = 1, but the type of that attribute (Foo) has no coercions declared. So, either remove the 'coerce = 1' bit, or add something to your Foo type explaining how to coerce it from some other type.
Re: the perl version support policy
On Fri, Jan 10, 2014 at 01:02:37AM -0800, Darren Duncan wrote: Does that policy apply to commercial operating systems as well, where people may choose to run older OSs on purpose, but may want to run newer Perl? For example, lots of Mac OS X Snow Leopard installs out there, and it came with Perl 5.10.1. In contrast, Mac OS X Mavericks comes with 5.16.2. Or should we expect people in that situation would install their own Perl if they want newer Moose? -- Darren Duncan I would say yes. The fact that Mac OS 10.6.8 (which I run on my primary development box at home) only has perl 5.10.1 is not relevant given that there is a newer version of the OS (10.9) available. Also note that any change in the minimum supported Perl version is not likely to have any effect on the *actual minimum version required*, at least in the short term. We will generally continue to accept patches for older Perls, so long as they do not hinder current or future development. I would expect Moose to continue to work on perl 5.8.x as long as all its dependencies also continue to do so. -- Anti-intellectualism has been a constant thread winding its way through our political and cultural life, nurtured by the false notion that democracy means that 'my ignorance is just as good as your knowledge.' - Isaac Asimov . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++
Re: [Still Failing] moose/Moose#375 (stable/2.12 - c8dcfd0)
For now, I've changed the github moose organization's email to mine -- et...@cpan.org. We'll come up with a better solution soon, but you won't be spammed anymore. I'm terribly sorry about this. On Wed, Nov 27, 2013 at 07:12:49AM -0800, Ovid wrote: I have to agree. I'm going to set up a filter to auto-delete these emails. Cheers, Ovid -- IT consulting, training, international recruiting http://www.allaroundtheworld.fr/. Buy my book! - http://bit.ly/beginning_perl Live and work overseas - http://www.overseas-exile.com/ On Monday, 21 October 2013, 22:18, Bob goolsby bob.gool...@gmail.com wrote: Travis -- Are you certain that the Moose Mailing list has a reasn to be receiving this? And what woulf that be?? B
Re: namespace Interface:: ?
On Sat, Oct 19, 2013 at 08:58:56AM +1300, Kent Fredric wrote: On 19 October 2013 08:53, Caleb Cushing xenoterrac...@gmail.com wrote: Anyone have any opinions on a namespace for roles that just do requires()? (and/or maybe do full signatures with an around). Role:: seems acceptable for this purpose imo. Just because a Role has no implementation details other than requires doesn't make it lesser than a role. I don't think a top level interface is generally appropriate for these sorts of things -- it should be primarily be named for the type of thing it's doing, not how it happens to be implemented. This also reminds me of the earlier discussion (a few months back, on this list) around MooseX vs MooseY. -- The thing I love most about deadlines is the wonderful WHOOSHing sound they make as they go past. - Douglas Adams . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++
Re: MooseY namespace
On Mon, Jun 10, 2013 at 01:24:31PM -0500, Caleb Cushing wrote: Basically this is just a suggestion for things that don't make sense in a context outside of Moose, of course like MooseX people will probably abuse it. At least it'd be giving them a place to go, instead of just saying, you have to leave but you can't stay here (in a place you can't enforce that). FWIW I just uploaded: https://metacpan.org/module/MooseX https://metacpan.org/module/MooseY in order to document the namespaces. Patches welcome!
Re: Accessing object constructors from the 'main'
On Sat, Jun 08, 2013 at 03:26:37AM -0400, Faelin McCaley Landy wrote: The Moose::Manual is very well written, but is definitely lacking in explanation of a very key step in product development: how on Earth do you actually use your objects in a script?! Like any other module, you need to load it first, via 'use': use Obj; my $obj = Obj-new(...); If you haven't read it, 'perldoc -f use' contains some useful tidbits of knowledge (as well as a smattering of esoterica).
Re: Moose::Object-equals();
On Sat, Jun 08, 2013 at 05:43:28PM -0500, Caleb Cushing wrote: a while back I wrote a piece of code that was basically a generic equals method for objects. I'm wondering if I patched moose to give objects this functionality if it'd be accepted? I would lean towards providing this via an external role, at least at first.
please test Moose-2.0900-TRIAL - changes to Num behaviour
Moose version 2.0900, released as a trial (unindexed) release this weekend, changes the semantics of the Num type constraint to be much more strict. The old, more lax behaviour is available as MooseX::Types::LaxNum if you were relying on it. More details are available at https://rt.cpan.org/Public/Bug/Display.html?id=70539 and in Moose::Delta. Please smoke-test this version against your applications, and report any issues to us. We plan to release this as version 2.1000 in approximately a month's time. Thanks again to Upasana Shukla for the implementation! -- You will always be lucky if you know how to make friends with strange cats. - colonial American proverb . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++
Re: Short-circuit before
On Mon, Apr 29, 2013 at 10:45:57AM -0700, Bill Moseley wrote: What we are after is somewhat of a plugin system built with Roles where a method in each Role is called in some defined order and once successful no more are run. Anyone have a better suggestion than our before authenticate approach? (in principle) roles should be able to be applied in any order and not be aware of/care about what other roles have been applied. If you need method modifiers to be aware of each other's existence, I would suggest creating an attribute (via another role, that the other roles would 'requires' to be applied) which can share the necessary state information. Altneratively, you might find the augment/inner method modification pattern to be of use -- a method can always opt to not call inner() if it has had its preconditions satisfied already. (Actually, this is probably better than my first suggestion.) -- Love is grand, divorce is a hundred grand. . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++
Re: BUILD called twice.
On Thu, Feb 14, 2013 at 12:05:02PM -0600, Dave Rolsky wrote: This is definitely a bug but it might be tricky to fix. Basically, method modifiers effectively copy the modified sub into the class that has the modifier. Moose then sees a BUILD in the subclass and baseclass and dutifully calls both. But as you point out, what you did is just wrong anyway. The whole point of BUILD is that defining it in subclasses doesn't hide the parent's implementation. The only time you need modifiers on BUILD is when you want a role to modify BUILD. Would it be sensible to warn in this case - when the BUILD sub is copied from the base class into the subclass to be modified? That would force the user to create an empty BUILD first before modifying it. I can't think of a case where this behaviour is actually intentionally wanted.
Re: Replacing use base with use parent
On Tue, Oct 09, 2012 at 11:14:02AM -0500, Jesse Luehrs wrote: parent is dual-life, so it wouldn't be a case of dropping support, it would just be an extra dependency for 5.8. That said, an extra dependency for no actual reason does seem a bit questionable (which is why I was asking for the reasoning). Have you looked at the base.pm code? It needs to die as quick a death as we can bring it. -- Three out of four experts want to know who the fourth guy is. . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++
Re: Version checking with MooseX::Storage::Engine
On Wed, Sep 26, 2012 at 02:07:41PM -0700, Bill Moseley wrote: snipped ... But, I'm not sure it makes sense to have MooseX::Storage so restrictive. A change in versions doesn't mean incompatible serialized objects. Is that version check too agressive? Maybe the strategy used by Storable might be useful here - only bump the version when the serialized format becomes incompatible. That would mean the user needs to indicate this somehow, rather than it being derived automatically.
Re: Test Failures: Foo already has a metaclass
On Tue, Sep 04, 2012 at 01:27:43AM -0700, Ovid wrote: If anyone can suggest where to look to solve this error, or what other information I can provide to help diagnose it? My searches on Google have turned up nothing. Is it convenient for you to perlbrew up a new installation of the same perl version that you're using, and try to install Moose there? That will at least tell us whether it's something particular to your machine, or due to some other module in your current install. If that installs cleanly, next I would suggest upgrading all Moose dependencies to their latest version - e.g. cpanm --installdeps Moose, again if convenient - logging the output, to determine which modules were upgraded and from what versions. -- While her schoolmates were worrying about boys and hairstyles, she was reading science fiction and worrying about nuclear winter, ozone holes and resource depletion. Her teachers called it escapism. . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++
Re: Wrapping builder from attribute trait?
On Fri, Apr 27, 2012 at 11:24:46AM -0400, Maddy, Noel wrote: Handling a builder isn't quite that easy -- if the builder method is defined before the attribute, then it's a simple add_around_method_modifier in _process_options. You can wrap Moose::Meta::Attributes::_call_builder, and its equivalent that produces an inlined version at make_immutable time. -- Ill fares the land to hastening ills a prey, where wealth accumulates, and men decay. Oliver Goldsmith (1728-1770), _Deserted Village_ . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++
MooseX::Getopt change to --help
MooseX-Getopt-0.42-TRIAL contains a change where requesting usage information via --help, --usage or --? will now print to stdout and then exit with status 0, rather than dying. Since there is a small chance this may break other releases, this is a trial release for now. I will likely make this a real release in a week or two if I don't hear anything, so if this affects you, or if you have any other comments, please let me know! http://metacpan.org/release/ETHER/MooseX-Getopt-0.42-TRIAL -- It's hard to get a man to understand something when his salary depends upon his not understanding. - Upton Sinclair . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++
Re: provide alternate init arg for an attribute
On Tue, Apr 10, 2012 at 03:47:12PM -0500, Caleb Cushing wrote: http://stackoverflow.com/questions/10051181/how-can-i-provide-an-alternate-init-arg-for-an-attribute-in-moose I'm trying to add an alternate name/init_arg for some attributes in my objects. MooseX::Aliases does this behavior (but with some features I don't want, and some things that ultimately make it unusable for what I need ). I'm not sure what things I might be missing in my linked code to make it work, the trait appears to be added right, but around initialize_instance_slot doesn't get called. Which magic have I not pulled out of MooseX::Aliases that I need to accomplish this? I'm still confused as to how this is different than what you need. First you say but creating an alias also creates accessors and then what I'm trying to do allow setting of the accessor via the name of the label I'm adding to the attribute via Meta Recipe3. -- which is exactly what MooseX::Aliases does. You appear to want to be able to set the attribute with the new name *in construction*, as well as *at runtime* via a new accessor - correct? so is this not the same as: has attr = ( is = 'rw', isa = 'Str', init_arg = 'attribute', accessor = 'attribute', ); so these tests will hold true: isnt(exception { Class-new(attr='foo') }, undef, 'cannot construct with the attr name'); my $obj; is(exception { $obj = Class-new(attribute = 'foo') }, undef, 'can construct with the attribute name'); ok(exists($obj-{attr}, 'the attr slot is used for storage'); is(exception { $obj-attribute('bar') }, undef, 'can alter the value with the attribute accessor'); ok(!$obj-can('attr'), 'no attr method exists'); If I am wrong, please correct these tests to demonstrate the desired behaviour. -- It is not because things are difficult that we do not dare; it is because we do not dare that things are difficult. - Seneca . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++
Re: Pattern for configuring child objects.
On Thu, Feb 23, 2012 at 12:57:26PM +0700, Bill Moseley wrote: I often have classes that abstract out the work of fetching data from multiple sources -- so I have attributes that hold instances of the objects that do the actual work. Each of these objects need their own config. I've used three approaches to pass config to the contained objects, but each seems a bit cumbersome. Just wondering if there's other ideas. One is to have a HashRef attribute in the parent that just gets passed to the child object's constructor. This doesn't work so good if the class is turned into a command line tool. I've also use a configuration class and pass an instance of that from the parent to the child. Essentially the same as the hashref approach. Whoa whoa whoa, stop right there. Have you seen MooseX::SimpleConfig and MooseX::Getopt? This is a very common design pattern in Moose: package MyChild; use Moose; with 'MooseX::Getopt', 'MooseX::SimpleConfig'; has configfile = ( is = 'ro', isa = 'Str', documentation = 'the configfile for MyChild', default = sub { my $class = shift; $class = blessed($class) || $class; return '/some/path/myclass_config.yml'; }, ); has $_ = ( is = 'ro', isa = 'Str', ) foreach @my_config_var_names; package Container; use Moose; has child = ( is = 'ro', isa = 'MyChild', lazy = 1, default = sub { my $self = shift; MyChild-new_with_config(%otheroptions); }, handles = { %delegations_here, }, ); # usecase 1: MyChild springs into existence on its first use, already # pre-configured with values from myclass_config.yml. $container-child-somesub; # usecase 2: use MyChild on its own, from a wrapper script. @ARGV is # automatically parsed via MooseX::Getopt and used as constructor args for # MyChild. The config file is also parsed and used for any configs that # aren't overridden from the command line. #/usr/bin/env perl use MyChild; my $child = MyChild-new_with_options; ./myscript --opt1 val1 --opt2 val2
Re: General Moose/Perl OO question
If that code looks too long and redundant to you, you may want to check out MooseX::Runnable, which takes care of constructing the object and calling -run() on it for you. PS. I'm not sure why you are wanting the class to be a singleton; that's usually a bad idea, and is orthogonal to the considerations of MooseX::Getopt and MooseX::Runnable anyway. On Thu, Feb 09, 2012 at 06:21:10PM +, sh...@comcast.net wrote: This begs a question: what to put in the main program if the class knows all it needs to run? -- Society is like a stew. If you don't keep it stirred up you get a lot of scum on the top. - Edward Abbey . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++
Re: MooseX::OmniTrigger
On Mon, Dec 19, 2011 at 11:40:32AM -0700, Todd Lorenz wrote: Unlike standard triggers, omnitriggers will fire on any initialization, setting, or clearing of the attribute value, and they're protected from recursion. (And they eliminate a couple of very esoteric bugs I found with standard triggers.) Can you elaborate on these bugs? -- Sometimes there is a silver bullet for boosting software engineering productivity. But you need to shoot the right person. - Craig Andera . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++
Re: MooseX::OmniTrigger
On Thu, Dec 22, 2011 at 02:36:00PM -0700, Todd Lorenz wrote: Hi, Karen, sure. I should say I *suspect* they're bugs based on my expectations of trigger behavior. I should also say they're extremely minor and probably aren't affecting anyone anywhere. They're in mooseisms.t. My explanation of #2 is pretty flip -- I didn't figure anyone would ever actually read it. Let me know if it needs translation. Using: https://github.com/trlorenz/MooseX-OmniTrigger/blob/master/t/007-mooseisms.t # POSSIBLE MOOSE BUG #1. DURING A REBLESS, REGULAR TRIGGERS WILL FIRE FOR # ANY ATTRIBUTES THAT HAVE AN UNDEFINED init_arg AND BEGAN THE REBLESS WITH # A VALUE. This sounds suspiciously similar to a fix I made for 2.0009: When an object is reblessed, triggers are called on attributes that are set during the reblessing. To clarify, triggers were not called for attributes that were being *added* (initialized, or altered) during the reblessing, as rebless() allows the supply of additional constructor arguments -- but possibly this is a red herring and there is no connection. I've confirmed this behaviour with my own tests, and indeed the attr must have init_arg=undef for the trigger to fire during a rebless. IMHO this is definitely a bug and should be fixed. #2 also sounds like a real issue (it is long so I won't repeat it here). Todd, do you have a Moose commit bit? It would be of significant value if you were to commit some TODO tests to the Moose repository so these issues were documented, and/or write them up as separate RT tickets. (You can submit your ssh public key via the instructions in Moose::Manual::Contributing, or hop on irc.perl.org #moose.) -- I do not fear computers. I fear the lack of them. - Isaac Asimov . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++
Re: Design Pattern for Validation
On Tue, Oct 11, 2011 at 04:30:25PM +0200, Peter Gordon wrote: I am trying to find a decent design pattern for Moose validation of user input. All the Moose examples I have found either assume that the data is correct or else dies. ... From an OOP perspective, it seems to me that the validation performed by the subtype should be part of the class and not something that is just floating around. Agreed - since we already have the class's constraints right there in the class definition, we can just use existing moose code to perform data validation in an object instance. There is also no reasonable way to trap the error, and report back to the user that there was an error. And I am not a fan of try/catch. Check out MooseX::Constructor::AllErrors - this is exactly what it was designed for. You still need to use a try block, but this is not a code smell on its own -- and you will get *all* type violation errors back (as well as other errors like missing attributes that are required=1, etc), in a tidy object that you can query to get the nature of the error(s) that occured. Example (uses TryCatch): my $obj; try { $obj = $class-new(%args); } catch ($exception) { my $meta = Class::MOP::class_of($exception); my $message = blessed $meta $meta-isa('Moose::Meta::Class') ? join('; ', map { $_-message } $exception-errors) : $exception; log_error(failed to construct a $class: , $message); } PS. As an aside, I gather from irc #moose that a few folks have been looking into other nicely-formed exception classes for Moose - if the same API could be used as in MX::C::AE, then the above code block will work in other situations as well as at construction time. -- Sometimes there is a silver bullet for boosting software engineering productivity. But you need to shoot the right person. - Craig Andera . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++
Re: Moose Type Constraints violations to warnings?
On Fri, Jun 10, 2011 at 03:06:29AM -0700, Ovid wrote: When I declare a parameter as follows: has 'some_val' = ( is = 'rw', isa = 'Int', ); Later if I do $object-some_value(foobar), it blows up with a stack trace because of the type constraint violation. Without using signal handlers, is there some way I can convert that exception into a warning except when something like $ENV{HARNESS_ACTIVE} is true? Preferably on a per-attribute basis? I see a few options: 1. Why not simply use a Str type instead of Int, if you're not absolutely sure that the provided value is an Int? Then you'd be able to see the value that was passed in, even if it wasn't a number. 2. Define a Str-to-Int coercion that selected an appropriate default if the value provided wasn't an int. You could also log a warning whenever the coercion is run, to catch these issues in testing. 3. Alternatively, you could wrap your calls to setters and constructors with a try/catch block using your exception handling package of choice (I recommend Try::Tiny). You'd have to examine the stack trace you get back to see what type of problem occured, and then replace the bad value with a better one. MooseX::Constructor::AllErrors can make this easier, but that's a Moose, not Mouse, solution. Given the context you've provided, I'd lean towards #2.
Re: _can_be_made_compatible_with Errors during Build
Do you have the latest namespace::clean and Package::Stash intalled? On Fri, Feb 04, 2011 at 10:15:18AM +0100, Rolf Schaufelberger wrote: Hi, when upgrading by Moose I get a lot of errors like this : t/300_immutable/007_immutable_trigger_from_constructor.t .. Can't locate object method _can_be_made_compatible_with via package Moose::Error::Default at /usr/local/lib/perl/5.10.1/Class/MOP/Class.pm line 375. BEGIN failed--compilation aborted at t/300_immutable/007_immutable_trigger_from_constructor.t line 13. t/300_immutable/007_immutable_trigger_from_constructor.t .. Dubious, test returned 9 (wstat 2304, 0x900) No subtests run nevertheless, Moose installs (1.21), but is that anything I have to worry about ? (System is ubuntu 10.04 LTS, Class::MOP is 1.12) Rolf Schaufelberger -- The integral of t squared dt From 1 to the cube root of three, When times the cosine Of three pi over nine: Is the log of the cube root of e! . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: MooseX::NonMoose for Roles?
On Fri, Jan 28, 2011 at 09:29:04PM +0100, Zbigniew Lukasiak wrote: Are there any sane options for building Moose::Roles out of Non Moose classes? Or maybe it is trivial? The thing about roles is they aren't instantiated, so you can't really do: package MyApp::Role::Foo; use base 'Some::Other::Class'; use Moose::Role; ...because there is no way to call up the inheritance tree to get at methods in Some::Other::Class. However, if you imported functions from that class into your role, you can make them available in your role just the same as if you had implemented them into your role itself. Perhaps can you describe an example of what you want to do? -- Historic continuity with the past is not a duty, it is only a necessity. - Oliver Wendell Holmes, Jr. . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: MooseX::NonMoose for Roles?
On Fri, Jan 28, 2011 at 12:35:38PM -0800, Karen Etheridge wrote: However, if you imported functions from that class into your role, you can make them available in your role just the same as if you had implemented them into your role itself. ..However that only works for functions, not anything else (like any state that would be stored in the class - due to it not being instantiated). Bottom line, do what Jesse and Hans said and use delegation instead :) -- Everything has been thought of before, but the problem is to think of it again. - Johann von Goethe . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: request for merge: replace Test::Exception with Test::Fatal
On Sun, Oct 24, 2010 at 01:23:57PM -0400, Ricardo Signes wrote: The branch rfc/test-fatal completely removes any dependency on Test::Exception, and thus on Sub::Uplevel. I had originally planned to rewrite all the test files, but this quickly became too boring and overwhelming. Instead, after the first pile of rewriting, I wrote a thin API compatibility layer with Test::Exception. It would be nice to continue to remove its use, but I think it is totally safe. I accidentally force-pushed over your branch; I am so sorry! :( :( :( I couldn't sleep last night so I created branches (of the same name, unfortunately) in Moose and CMOP and converted all test files. It turned out to be not terribly difficult, after I had written an appropriate perl -pi regexp. But anyway, a thousand apologies; please push your branch back up!
Re: request for merge: $type_constraint-assert_coerce
On Fri, Oct 22, 2010 at 08:05:04PM -0400, Ricardo Signes wrote: The code is in rfc/assert_coerce, and I am giving it a +1 for merging as a small, useful method built entirely in terms of existing features. +1. Now I can easily coerce crappy user input via: use Moose 1.18; my $cleaned_data = MyApp::Types::TypeName-assert_coerce($crappy_user_input); ...where TypeName is declared with MooseX::Types. -- The graveyards are full of indispensible men. - Charles de Gaulle . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: deprecating (part of) lazy_build
On Thu, Sep 30, 2010 at 02:35:13PM -0400, Hans Dieter Pearcey wrote: We don't like the fact that lazy_build autogenerates public clear_$attr and has_$attr methods for you 1) reuse 'builder', i.e. 'builder = 1' is special cased to be the same as 'builder = _build_$attr' Someone said what about subs named '1'? but I think we're probably all OK with ignoring anyone crazy enough to do that. That was me, but I want to make clear that even I am not so crazy to do that :) 3) make the clearers and predicates generated by lazy_build issue deprecation warnings the first time they're called that suggest specifying a clearer and/or predicate, and ship a Moose::Deprecated::LazyBuildPublicMethods (or whatever) to shut them up. I like option #3 best, but doing #1 as well might be quite useful too -- I can forsee an outcry what, you mean I need to type out my builder method names? Upside: people who aren't affected don't have to care, people who are affected have a simple solution (just add 'use Moose::Deprecated::blahblah' to your class). Also, we never have to actually remove the clearers/predicates and risk breaking people's code if we don't want to. deprecations++. Thanks for writing this up, Hans! -- A: To be or not to be. Q: What is the square-root of four b-squared? . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: Class::MOP 1.05 installation fails
I have the same test failure. % perl -V:archname archname='i386-linux-thread-multi'; % cat /proc/version Linux version 2.6.18-53.1.21.el5 (mockbu...@builder6.centos.org) (gcc version 4.1.2 20070626 (Red Hat 4.1.2-14)) #1 SMP Tue May 20 09:34:18 EDT 2008 On Mon, Aug 23, 2010 at 04:54:46PM +0400, Konstantin A. Pustovalov wrote: Tried to install recent update Class::MOP 1.04 - 1.05. Failed with: snip t/003_methods.t ... 1/? # Failed test 'get_method_list handles constants properly' # at t/003_methods.t line 368. # Structures begin differing at: # $got-[0] = 'BAR' # $expected-[0] = 'quux' # Failed test '_get_local_methods handles constants properly' # at t/003_methods.t line 375. # Structures begin differing at: # $got-[0] = 'BAR' # $expected-[0] = 'quux' # Looks like you failed 2 tests of 71. t/003_methods.t ... Dubious, test returned 2 (wstat 512, 0x200) /snip perl v 5.8.8 x86_64-linux-thread-multi Regards, -- Konstantin A. Pustovalov -- An eye for an eye leaves the whole world blind. - Mahatma Gandhi . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: Class::MOP 1.05 installation fails
Class::MOP 1.06 fixes this. Thanks guys! On Mon, Aug 23, 2010 at 09:23:44AM -0700, Karen Etheridge wrote: I have the same test failure. ... -- If you can talk brilliantly enough about a problem, it can create the consoling illusion that it has been mastered. - Stanley Kubrick . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: Some documentation questions/suggestions
On Fri, Jul 30, 2010 at 05:57:27PM +0300, Offer Kaye wrote: On Thu, Jul 29, 2010 at 10:27 PM, Chris Prather wrote: These are generally excellent suggestions. If you would like to supply an ssh key someone can get you commit access to update the relevant POD. Sorry but I don't know how to get an ssh key :( Here's some instructions for generating keys on windows: http://superuser.com/questions/141962/what-is-an-ssh-key On unix/linux/OSX, you can use ssh-keygen. -- One million lemmings can't be wrong. . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: Some documentation questions/suggestions
On Fri, Jul 30, 2010 at 11:30:50PM +0300, Offer Kaye wrote: Thanks Karen - I forgot to say I'm on Windows. So now I've used PuTTy to generate a private/public key pair, do I just paste the public key to the list? Yes exactly. (Never give anyone your private key; it shouldn't even be transfered to another machine. Only the public key is stored on other machines, to be used to verify your identity.) After that, you can follow the guidelines at Moose::Manual::Contributing for setting up the Moose repository and creating a branch for your documentation updates. -- Ten people who speak make more noise than ten thousand who are silent. . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: Another MooseX::Runnable/MooseX::Getopt/MooseX::Configfile issue
Please review branch topic/no_auto_help. On Fri, Jun 25, 2010 at 11:14:00AM -0700, Karen Etheridge wrote: SOLVED (as well as my previous post here: http://www.nntp.perl.org/group/perl.moose/2010/06/msg1675.html) Getopt::Long::Parser is being invoked with the wrong config options in MooseX::Getopt::Basic. the no_auto_help option must be passed, or Getopt::Long will see the --help flag and proceed to call pod2usage (with an undefined message), and exit. I will submit a ticket to the MooseX-Getopt queue, and a patch. -- This troubled planet is a place of the most violent contrasts. Those that receive the rewards are totally separated from those who shoulder the burdens. It is not a wise leadership. - Spock, The Cloud Minders, Star Trek . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: Another MooseX::Runnable/MooseX::Getopt/MooseX::Configfile issue
On Thu, Jun 24, 2010 at 05:41:16PM -0700, Karen Etheridge wrote: On Thu, Jun 24, 2010 at 05:22:31PM -0700, Karen Etheridge wrote: why does this work: perl run.pl Foo (prints: I lived!) but this does not: perl run.pl Foo --help Another potential clue: this also succeeds: mx-run -I. Foo --help Although new_with_options() is being invoked just the same in all circumstances, as far as I can tell. SOLVED (as well as my previous post here: http://www.nntp.perl.org/group/perl.moose/2010/06/msg1675.html) Getopt::Long::Parser is being invoked with the wrong config options in MooseX::Getopt::Basic. the no_auto_help option must be passed, or Getopt::Long will see the --help flag and proceed to call pod2usage (with an undefined message), and exit. I will submit a ticket to the MooseX-Getopt queue, and a patch. -- The greatest discovery of my generation is that human beings can alter their lives by altering their attitudes. - William James . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Another MooseX::Runnable/MooseX::Getopt/MooseX::Configfile issue
If I write a package like this: package Foo; use Moose; with 'MooseX::Runnable', 'MooseX::SimpleConfig', 'MooseX::Getopt'; sub run { print I lived!\n; } 1; and a MooseX::Runnable script like this: use strict; use warnings; use lib '.'; use MooseX::Runnable::Run; my $task = shift @ARGV; run_application $task, @ARGV; why does this work: perl run.pl Foo (prints: I lived!) but this does not: perl run.pl Foo --help The second case dies in the middle of Getopt::Long::GetOptionsFromArray. This duplicates how GetOptionsFromArray is being called: perl -MGetopt::Long -we'\ my $opt_parser = Getopt::Long::Parser-new( config = [ qw( pass_through )] );\ $opt_parser-getoptions( configfile=s = \$configfile );'\ -- --help ... and works just fine, so it would appear something is getting screwed up in an eval block... Help? :( -- Totally mad. Utter nonsense. But we'll do it because it's brilliant nonsense. - Douglas Adams . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: Another MooseX::Runnable/MooseX::Getopt/MooseX::Configfile issue
On Thu, Jun 24, 2010 at 05:22:31PM -0700, Karen Etheridge wrote: why does this work: perl run.pl Foo (prints: I lived!) but this does not: perl run.pl Foo --help Another potential clue: this also succeeds: mx-run -I. Foo --help Although new_with_options() is being invoked just the same in all circumstances, as far as I can tell. -- You cannot find peace by avoiding life. - Virginia Woolf . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: Defining attributes
On Tue, Jun 22, 2010 at 10:48:21AM -0500, Evan Carroll wrote: And the forbidden Triple Jeopardy question? What ways can you have prevented this with a much more simplistic failure? I believe it has already been said that there will be a clearer error message added for when one attempts to use a Moose keyword. This should open up the ability for you to create attributes named after Moose keywords that are totally inaccessible to code that doesn't explicitly use meta. That doesn't sound like a good idea in practice, but go ahead if it amuses you. System Lord of the Internets Hey how do I get a Lord title? Is there an application I can fill out? -- Do not engage in useless activity. - Miyamoto Musashi, Japanese Samurai, 1645 . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: Those error messages
On Fri, Jun 11, 2010 at 07:37:27AM -0700, Bill Moseley wrote: Our developers (and people that handle staging) have been remarking about very low signal to noise error messages since moving some of our code to Moose. Unless you're doing a lot of runtime role application or other meta magic, virtually all the errors you should be seeing from Moose happen at compile time during development, so I would expect you would be screening these out before you get to staging. Is this not your experience? Moose errors are verbose, but like any stack trace, usually the most relevant bits are right at the beginning. You could always add a custom __DIE__ handler to catch these and truncate them, and divert the unmodified version to a different log file. However, IMHO you should be putting more effort into fixing the errors, rather than making them look pretty :) -- What a joy to think the future is unwritten. - Bruce Sterling . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: (Another) Error metaclass problems with Moose 1.07
On Tue, Jun 08, 2010 at 03:33:46PM -0500, Chris Fields wrote: You can ignore that previous post. After going through the code and seeing how overly complicated I made things, I decided to go in and dramatically simplify exception handling, and somehow managed to get everything working using a custom error metaclass. I may go back to Exception::Class at some point, but it works great for now. Thanks! Another refactor for the win! :) -- Many men of course became extremely rich, but this was perfectly natural and nothing to be ashamed of because no one was really poor - at least no one worth speaking of. - Douglas Adams . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Help with MooseX::Runnable, MooseX::Getopt, MooseX::SimpleConfig...
Recently I filed a bug against MooseX::Getopt while I was trying to get --help working, but it was a bit incoherent: https://rt.cpan.org/Ticket/Display.html?id=57683 I figured out how to get this to work by writing my own _getopt_full_usage method (code below), but am now running into some more interesting behaviour caused by the interaction of MooseX::Runnable with MooseX::Getopt and MooseX::SimpleConfig. Hopefully this will make sense to someone. Let's start with a simple working module... package Module; use strict; use warnings; use Moose; use MooseX::ClassAttribute; with 'MooseX::Getopt' = { excludes = [qw(_getopt_full_usage)] }; with 'MooseX::Runnable'; #with 'MooseX::SimpleConfig'; # intentionally commented out for now has [qw(help usage)] = ( is = 'ro', isa = 'Bool', documentation = 'Prints this usage documentation.', ); class_has instructions = ( is = 'ro', isa = 'Str', init_arg = undef, # don't allow in constructor default = 'TODO: usage text' ); # called when --help or --usage is used on command line sub _getopt_full_usage { my ($this, $usage) = @_; print $this-instructions, \n; print $usage-text, \n; exit; } sub run { my $this = shift; print ### in run, with extra args @_\n; } no Moose; __PACKAGE__-meta-make_immutable; 1; When run from the command-line in this form, the expected usage information is printed: $ mx-run -I. Module --help TODO: usage text usage: mx-run [long options...] --help Prints this usage documentation. --usage Prints this usage documentation. Now, if I uncomment the usage of MooseX::SimpleConfig, I get an error from deep within Getopt::Long (it seems to be attempting to parse some pod data, but I can't figure out where it is trying to find it): $ mx-run -I. Module --help Can't open mx-run ... Module: No such file or directory at /usr/lib/perl5/5.8.8/Getopt/Long.pm line 1427 TODO: usage text usage: mx-run [long options...] --configfile --helpPrints this usage documentation. --usage Prints this usage documentation. To add to the interesting behaviour, if I create a separate script to invoke the module: $ cat run.pl #!/usr/bin/perl use strict; use warnings; use lib '.'; use MooseX::Runnable::Run; @ARGV = ('--help') unless @ARGV; run_application 'Module', @ARGV; # ./run.pl no output at all! Has anyone gotten all three of these MX modules to work together in harmony? The examples I provided are fairly simple, but something surely must be missing. -- When I see an adult on a bicycle, I do not despair for the future of the human race. - H. G. Wells . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: Moose and object specification versions
On Tue, May 18, 2010 at 11:59:57PM +0200, Heiko Jansen wrote: Dear Moose-icians, Heh, I like that one! But how am I supposed to tackle this problem using Moose/PRANG? Changing the 'isa' property of Moose attributes at runtime based on the value of another attribute (holding the MODS version number) seems weird. I'd be glad if someone could describe possible solutions and/or point to existing code solving this kind of problem. How about a parameterized role that took the version number as a parameter? Then you could define the attribute type constraints with that version in mind, and all the work would be done at compile time. -- Each has his past shut in him like the leaves of a book known to him by heart and his friends can only read the title. - Virginia Woolf . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: Notes about MooseX::Role::Parameterized
On Thu, Apr 22, 2010 at 02:54:07PM -0700, Kate Yoak wrote: Just a couple of notes that would be of use if they were in the documentation: 1. The bad news: Because of the weirdness of role{} block, the child, nor the role cannot be declared within the same file with the script. (Like you might do while trying to test sample functionality!) Are you sure? e.g. have you tried including each namespace in its own block? Otherwise, each package is polluting each other's namespaces. (Alternatively, you could use namespace::autoclean.) { package MyRole; use MooseX::Role::Parameterized; role {}; 1; } { package MyClass; use Moose; with MyRole = {}; 1; } package main; my $obj = MyClass-new(); print obj is: . $obj-dump(1); -- Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. - Brian W. Kernighan . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: Notes about MooseX::Role::Parameterized
On Thu, Apr 22, 2010 at 03:25:41PM -0700, Kate Yoak wrote: Another issue: Can parameter use builder and have it defined within the same module? I've tried parameter foo = (is = 'rw', builder = '_foo'); with _foo() defined above this statement, below it, inside the role block (pretty sure it fails before getting inside the role). No good. It says: Error: Class::MOP::Class::__ANON__::SERIAL::1 does not support builder method ... What should I do? You should have the builder method defined outside the role {} block, i.e. at the same level as the parameter declaration itself. Can you give an example where you would need to define the builder inside the role block? This sounds rather strange to me. -- I felt a kind of forlorn sense of being lost in a world of incredibly stupid and malicious dwarfs. - Aleister Crowley . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Maybe[Foo] type coercions
I'm having difficulty getting a type coercion to work that involves Maybes. I've looked at the deep coercion section of Moose::Manual::Types, and I'm not sure what I'm missing to get this to work? e.g. I'm running perl -MData::Dumper -MObject -MDateTime -I. -wle'my $o=Object-new(date=-00-00 00:00:00); print Dumper($o)' against this module, Object.pm: package Object; use Moose; use Moose::Util::TypeConstraints; use DateTime; use DateTime::Format::MySQL; has date = ( is = 'rw', isa = 'MaybeDateTime', coerce = 1 ); # this generates Attempt to free unreferenced scalar error! #has date = ( is = 'rw', isa = 'Undef | DateTime', coerce = 1 ); subtype 'DateTime' = as 'Object' = where { $_-isa('DateTime') }; subtype 'MaybeDateTime' = as 'Maybe[Object]' = where { $_-isa('DateTime') or not defined $_ }; coerce 'MaybeDateTime' = from 'DateTime' = via { return $_ }; coerce 'MaybeDateTime' = from 'Str' = via { print ### calling Str-MaybeDateTime coercion\n; # check for retarded mysql 4.x null times return if $_ eq '-00-00 00:00:00'; return DateTime::Format::MySQL-parse_datetime($_); }; coerce 'DateTime' = from 'Str' = via { print ### coercing Str $_ into DateTime\n; return DateTime::Format::MySQL-parse_datetime($_); }; 1; -- A dozen, a gross, and a score, plus three times the square root of four, divided by seven, plus five times eleven, equals nine squared and no more! . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: Maybe[Foo] type coercions
On Mon, Feb 15, 2010 at 06:31:24PM -0600, Jesse Luehrs wrote: On Mon, Feb 15, 2010 at 04:25:54PM -0800, Karen Etheridge wrote: I'm not sure what problem you're having, since you didn't post the error message, Oops sorry, it was: Attribute (date) does not pass the type constraint because: Validation failed for 'MaybeDateTime' failed with value -00-00 00:00:00 (not isa MaybeDateTime) at ... but you probably need the attribute definition to happen after the types are defined... pretty sure this would assume you have a class named 'MaybeDateTime'. Doh, of course! After moving the 'has' line to the end of the module, now I get: Can't call method isa on an undefined value at Object.pm line 15. ...where line 15 is the where line of the subtype 'MaybeDateTime' definition. However, I see that I'm dereferencing $_ before checking its definedness, so if I switch to: = where { not defined $_ or $_-isa('DateTime') }; ...then the object constructs properly! Hurrah! (I suspect that perhaps some of the coercions I have created are unnecessary; I'll look into that next to see if I can remove them.) doy++ :) -- Whoever acquires knowledge but does not practice it is as one who ploughs but does not sow. - Sa'di . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Attribute initializers - incorrect documentation
As mentioned on #moose yesterday, I have found an inconsistency in the documentation (I don't think this is a bug, as the actual behaviour looks reasonable and correct to me): The documentation for Class::MOP::Attribute 0.98 says: This option can be either a method name or a subroutine reference. This method will be called when setting the attribute's value in the constructor. Unlike default and builder, the initializer is only called when a value is provided to the constructor. The initializer allows you to munge this value during object construction. ..but in fact the initializer is called at any point the attribute is set (during construction, as well as after), as demonstrated by this simple example: package Foo; use Moose; has foo = ( is = 'ro', isa = 'Int', initializer = sub { my ($this, $value, $setref, $attr) = @_; print ### in foo initializer!\n; $setref-(2 * $value); }, default = 1, lazy = 1, ); has bar = ( is = 'ro', isa = 'Int', lazy = 1, default = sub { shift-foo + 1 }, ); sub BUILD { print ### in BUILD\n; } 1; perl -I. -MFoo -we'\ my $obj = Foo-new; \ print $obj-dump(1); \ print $obj-bar; \ print $obj-dump(1)' produces the output: ### in BUILD $VAR1 = bless( {}, 'Foo' ); ### in foo initializer! 3$VAR1 = bless( { 'bar' = 3, 'foo' = 2 }, 'Foo' ); -- Show me a piano falling down a mineshaft and I'll show you A-flat minor. . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: Attribute initializers - incorrect documentation
On Thu, Feb 04, 2010 at 02:17:32PM -0500, Hans Dieter Pearcey wrote: I'm not sure whether this is a bug or not, but we've been talking about giving initializer the axe for a while. Does anyone feel motivated by this to do so? I'm currently using an initializer attribute in $work code, to copy values out of $obj-attr1 into $obj-attr2 (both are objects) when attr1 is set, but I'm staring at the code again now and wondering why I didn't just write a trigger instead. Is there any behavioural difference between initializer and trigger methods that I'm missing? -- Tolerance is giving to every other human being every right that you claim for yourself. - Robert G. Ingersoll . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: Attribute initializers - incorrect documentation
On Thu, Feb 04, 2010 at 11:53:50AM -0800, Karen Etheridge wrote: On Thu, Feb 04, 2010 at 02:17:32PM -0500, Hans Dieter Pearcey wrote: I'm not sure whether this is a bug or not, but we've been talking about giving initializer the axe for a while. Does anyone feel motivated by this to do so? I'm currently using an initializer attribute in $work code, to copy values out of $obj-attr1 into $obj-attr2 (both are objects) when attr1 is set, but I'm staring at the code again now and wondering why I didn't just write a trigger instead. Is there any behavioural difference between initializer and trigger methods that I'm missing? Doh let me rephrase (of course they are different - trigger acts like an 'after' method modifier on the setter, whereas initializer acts like an 'around'). Is there anything one can do with an initializer that can't be done with a trigger? If one wants to change the value of an attribute if a particular value was assigned, one could simply call $attr-set_raw_value, but that bypasses type coercion and some other nice things. Calling set_value would cause an infinite loop in the trigger. The only other way through this that I see is to add a new meta-attribute method set_value_without_trigger, but that's gross! -- If you can talk brilliantly enough about a problem, it can create the consoling illusion that it has been mastered. - Stanley Kubrick . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: Attribute initializers - incorrect documentation
On Thu, Feb 04, 2010 at 11:58:10AM -0800, Karen Etheridge wrote: Doh let me rephrase (of course they are different - trigger acts like an 'after' method modifier on the setter, whereas initializer acts like an 'around'). Is there anything one can do with an initializer that can't be done with a trigger? If one wants to change the value of an attribute if a particular value was assigned, one could simply call $attr-set_raw_value, but that bypasses type coercion and some other nice things. Calling set_value would cause an infinite loop in the trigger. The only other way through this that I see is to add a new meta-attribute method set_value_without_trigger, but that's gross! doy set me straight: 12:34 ether so. after thinking through my post to the mailing list, I think there might be a use for initializers after all 12:35 ether there's no other good way of munging a value being assigned to an attribute, other than writing an explicit 'around' method modifier to the setter, and IMHO one should never have to depend on a setter's name 12:36 ether so what I'd do is simply change initializer so that it's always called on set, rather than just when $old_value is undef... if one passes $new_value and $old_value to the method, then one can still achieve the old behaviour if desired 12:37 @doy ether: accessor meta-trait 12:37 ether ah, to add on new behaviour in set_value? yes that would work 12:38 ether much better; thank you! I'm satisfied now: there is no usecase for an initializer that couldn't be achieved using either a trigger or by modifying the behaviour of the attribute's setter. -- Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Moose::Util::MetaRole parameters passed from Moose::Exporter
I'm having difficulty getting some Moose::Util::MetaRole arguments passed from Moose::Exporter (specifically, I want to apply a role to a metaclass directly from an existing Moose::Exporter call). Since from the documentation this appears to be a simple task, I must have missed something, so I'm going back to trying to get a simple example to work, i.e. re-implementing MooseX::Aliases trait. What is missing from this simple example? package MyApp::Foo; use MyApp::Export; has field = ( alias = 'alias', is = 'ro', isa = 'Int' ); 1; package MyApp::Export; use Moose (); use Moose::Exporter; also = [ qw(Moose) ], # pass some arguments for Moose::Util::MetaRole to be called in # init_meta... class_metaroles = { attribute = ['MooseX::Aliases::Meta::Trait::Attribute'], # in theory, I should just have to say this to add a role to my metaclass? # class = [ 'MyApp::Meta::Class::Trait::MyTrait' ], }, ); no Moose; 1; many thanks, -- Vote Cthulhu: For when you're tired of the lesser evil . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Re: Moose::Util::MetaRole parameters passed from Moose::Exporter
Update: if one removes this line from MyApp::Export: also = [ qw(Moose) ], ... and adds use Moose; to MyApp::Foo, things work fine (well rather, code execution gets up to Undefined subroutine MooseX::Aliases::_get_method_metaclass called at... which is expected because the methods in MooseX::Aliases weren't defined in this contrived example. Therefore, this looks to be a bug? I would expect it should be possible to bring in Moose via the also field without altering any other behaviour. PS. some of the documentation in Moose::Exporter and Moose::Cookbook::Extending::Recipe1 still refer to pre-0.93 class and field names, e.g. apply_metaclass_roles(), attribute_metaclass_roles, constructor_class_roles. On Fri, Jan 22, 2010 at 01:15:39PM -0800, Karen Etheridge wrote: What is missing from this simple example? snip -- Errors, like straws, upon the surface flow; He who would search for pearls must dive down below. - John Dryden . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Extracting the metaclass from a parameterized role
tl;dr version: no questions here, just some discoveries that I wanted to spread a little farther and get google-indexed :) A while back I posted on Stack Overflow about extracting the metaclass of the currently-composing class from within the role definition: http://stackoverflow.com/questions/1758884/how-can-i-access-the-meta-class-of-the-module-my-moose-role-is-being-applied-to ... which lead me to MooseX::Role::Parameterized (a continued two big thumbs up BTW), which lead me to a few discoveries that I wanted to mention here for posterity: 1. $args{consumer} only contains the metaclass of the target class at the first level of parameterization. If the parameterized role (Role::A) is further including another parameterized role (Role::B), then $args{consumer} in Role::B will actually contain the metaclass of the first parameterized role (MooseX::Role::Parameterized::Meta::Role::Parameterized), rather than (a possible subclass of) Moose::Meta::Class. In my application I'm nesting parameterized roles a few levels deep (the code is cleaner this way rather than having lots of nested if statements), so I've added a 'meta' parameter to the list of params being passed around: # when calling the sub-role: role { # isa Moose::Meta::Class my $meta = $args{consumer}; with Role::B = { # other parameters... metaclass = $meta, }; }; # and in the subrole: parameter metaclass = ( is = 'ro', isa = 'Moose::Meta::Class', required = 1, ); role { # isa Moose::Meta::Class my $meta = $params-metaclass; }; 2. $args{consumer} won't even be a metaclass in the case of a role application to a specific object instance -- in this case it will be the type of the object being applied to. role { my $meta = $args{consumer}; $meta = $meta-meta if not $meta-isa('Moose::Meta::Class'); }; Neither of these discoveries seemed obvious at first, so I wanted to pass it on to save others some heartache. I wonder if the true metaclass should perhaps be available via some sort of method call, to avoid the backflips I've done above -- I'm using all the code above as boilerplate in all my parameterized roles now. PS. Earlier today I was about to post here asking how one could apply a parameterized role to an object instance (as there was no example in the documentation), but in stepping through the Moose guts I discovered that indeed it is just as simple as for non-parameterized roles: (oh happy day) my $foo = My::Foo-new(); Moose::Util::apply_all_roles($foo, My::Role, { parameter = 'value' });
Extracting the metaclass from a parameterized role
(Apologies if this is a dupe; I've tried sending this a few times today and have been experiencing issues with my msmtp configs.) tl;dr version: no questions here, just some discoveries that I wanted to spread a little farther and get google-indexed :) A while back I posted on Stack Overflow about extracting the metaclass from inside a role definition: http://stackoverflow.com/questions/1758884/how-can-i-access-the-meta-class-of-the-module-my-moose-role-is-being-applied-to ... which lead me to MooseX::Role::Parameterized (a continued two big thumbs up BTW), which lead me to a few discoveries that I wanted to mention here for posterity: 1. $args{consumer} only contains the metaclass of the target class at the first level of parameterization. If the parameterized role (Role::A) is further including another parameterized role (Role::B), then $args{consumer} in Role::B will actually contain the metaclass of the first parameterized role (MooseX::Role::Parameterized::Meta::Role::Parameterized), rather than (a possible subclass of) Moose::Meta::Class. In my application I'm nesting parameterized roles a few levels deep (the code is cleaner this way rather than having lots of nested if statements), so I've added a 'meta' parameter to the list of params being passed around: # when calling the sub-role: role { # isa Moose::Meta::Class my $meta = $args{consumer}; with Role::B = { # other parameters... metaclass = $meta, }; }; # and in the subrole: parameter metaclass = ( is = 'ro', isa = 'Moose::Meta::Class', required = 1, ); role { # isa Moose::Meta::Class my $meta = $params-metaclass; # isa Moose::Object my $consumer = $meta-name; }; 2. $args{consumer} won't even be a metaclass in the case of a role application to a specific object instance -- in this case it will be the type of the object being applied to. role { my $meta = $args{consumer}; $meta = $meta-meta if not $meta-isa('Moose::Meta::Class'); # isa Moose::Object my $consumer = $meta-name; }; Neither of these discoveries seemed obvious at first, so I wanted to pass it on to save others some heartache. I wonder if it might be useful to offer an API to extract the metaclass, as the code above has essentially become boilerplate for all my parameterized roles.. PS. Earlier today I was about to post here asking how one could apply a parameterized role to an object instance (as there was no example in the documentation), but in stepping through the Moose guts I discovered that indeed it is just as simple as for non-parameterized roles: my $foo = My::Foo-new(); Moose::Util::apply_all_roles($foo, My::Role, { parameter = 'value' });
Re: custom trait
On Thu, Jan 14, 2010 at 01:45:18AM +0100, Dmitry Karasik wrote: ...I have no idea how to work around these problems... This means that I welcome patches and advices that would not only help me fix the rest of incompatibilities for today, but also would be in sync with the main ideology of Moose. Correct me if I'm wrong, but I think this is the advice that was being offered earlier today, that you were taking offense to? -- The eyes of others our prisons; their thoughts our cages. - Virginia Woolf . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
MooseX::Role::Strict + MooseX::Role::Parameterized
What would it take to gain the properties of MooseX::Role::Strict in MooseX::Role::Parameterized? I've been using strict roles everywhere and love them -- they've caught a few bugs that I'm sure would have been dreadful to track down otherwise; now I'm parameterizing a few of my roles and I'm mourning the loss of strict checking. I've been meaning to find the time to just sit down and do some experiments myself (I've done a bit of meta hacking with traits and Moose::Exporter), but I'd like to toss the question out there in case anyone else has thought along similar lines. -- Vehemence is no guarantee of truth. - Isaac Asimov . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)
Bug in MooseX::Aliases with MooseX::StrictConstructor?
There seems to be a bug with the way MooseX::Alias interacts with MooseX::StrictConstructor. Here is a repro case: package Foo; use Moose; use MooseX::StrictConstructor; use MooseX::Aliases; has attr = ( is = 'rw', isa = 'Str', alias = 'alias_attr', ); no Moose; __PACKAGE__-meta-make_immutable; 1; perl -I. -MFoo -wle'my $obj = Foo-new(alias_attr=blah); print $obj-alias_attr' Found unknown attribute(s) passed to the constructor: alias_attr at generated method (unknown origin) line 23 Foo::new('Foo', 'alias_attr', 'blah') called at -e line 1 If the make_immutable call is removed, the problem disappears. My guess is that make_immutable does not take the alias into account when inlining the constructor? -- End random acts of parenting. . ... . Karen Etheridge, ka...@etheridge.ca GCS C+++$ USL+++$ P+++$ w--- M++ http://etheridge.ca/ PS++ PE-- b++ DI e++ h(-)