Advertisement
Guest User

Using Moose to autogenerate MongoDB::OID

a guest
Jun 1st, 2011
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.41 KB | None | 0 0
  1. #!/usr/bin/env perl
  2. use strict;
  3. use warnings;
  4. use utf8::all;
  5. use Moose;
  6. use MongoDB;
  7. use MongoDB::OID;
  8. use Data::Printer;
  9.  
  10. {
  11.     package User;
  12.     use Moose;
  13.     use Moose::Util::TypeConstraints;
  14.    
  15.     class_type('MongoDB::OID');
  16.     coerce 'MongoDB::OID'
  17.         => from 'Str'
  18.             => via { MongoDB::OID->new($_) };
  19.    
  20.     has '_id' => (
  21.         is       => 'ro',
  22.         isa      => 'MongoDB::OID',
  23.         required => 1,
  24.         coerce   => 1,
  25.     );
  26.    
  27.     has 'name' => (
  28.         is       => 'rw',
  29.         isa      => 'Str',
  30.         required => 1,
  31.     );
  32.    
  33.     no Moose;
  34.     __PACKAGE__->meta->make_immutable;
  35. }
  36.  
  37. my $user1 = User->new(
  38.     _id  => '4de50e865c93120f5d000000',
  39.     name => 'Fred',
  40. );
  41.  
  42. p $user1;
  43. p $user1->_id;
  44.  
  45. ~~~~~~~~~~~~~~
  46. Output:
  47. ~~~~~~~~~~~~~~
  48.  
  49.  
  50. sidburn@sid:~/perl/mongo$ ./oid.pl
  51. User  {
  52.     Parents       Moose::Object
  53.     Linear @ISA   User, Moose::Object
  54.     public methods (4) : DESTROY, meta, name, new
  55.     private methods (1) : _id
  56.     internals: {
  57.         _id    MongoDB::OID,
  58.         name   "Fred"
  59.     }
  60. }
  61. MongoDB::OID  {
  62.     Parents       Moose::Object
  63.     Linear @ISA   MongoDB::OID, Moose::Object
  64.     public methods (10) : ("", BUILDARGS, build_value, DESTROY, get_time, meta, new, TO_JSON, to_string, value
  65.     private methods (1) : _build_value
  66.     internals: {
  67.         value   "4de61042acdcdc811f000000"
  68.     }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement