x
Loading
 Loading
Hello, Guest | Login | Register

The Moose is Flying, Part Two

The Moose object system enforces type, validates values, and coerces parameters to be the correct type.

Last month, I introduced the Moose object system by rewriting the sample code found in the perlboot man page to use Moose. Let’s continue the discussion and look at some of the features I didn’t cover last time.

Animal House

The role Animal included attributes name and color, and actions speak and eat. You can add a birthdate attribute to the Animal with:

 has ’born’ => (is => ’ro’); 

Since a birthdate isn’t mutable, it’s marked as read-only. By default, this attribute accepts any scalar, so these definitions are all equally valid:

 my $horse = Horse->new(born => ’yesterday’, name => ’Newbie’); my $cow = Cow->new(born => ’spring of 82’, name => ’Bessie’); my $mouse = Mouse->new(name => ’Minnie’, born => ’3/14/1929’); my $racehorse = RaceHorse->new(name => ’Slew’, born => [3, 5, 59]); 

You can use the Moose type system to narrow the permissible type of the birthdate attribute:

 require DateTime; has ’born’ => (is => ’ro’, isa => ’DateTime’); 

The isa parameter here declares that the born parameter must be a DateTime object, or at least something that responds true to UNIVERSAL::isa($thing,"DateTime"). Now, a run-time error occurs if you try to put anything in the born attribute other than a DateTime. Hence…

 my $horse = Horse->new(born => ’yesterday’, name => ’Newbie’); 

… fails, but this succeeds:

 my $horse = Horse->new(born => DateTime->now, name => ’Newbie’); 

The DateTime string for isa refers here to the…

Please log in to view this content.

Not Yet a Member?

Register with LinuxMagazine.com and get free access to the entire archive, including:

  • Hands-on Content
  • White Papers
  • Community Features
  • And more.
Already a Member?
Log in!
Username

Password

Remember me

Forgotten your password?
Forgotten your username?
Read More
  1. Helpful Tools for Software Developers
  2. The Github Hall of Fame
  3. Book'em, Github.
  4. This Week on Github: Stupid Ruby Tricks
  5. A Veritable Scatter Shot!
Follow Linux Magazine
Rackspace