SlideShare una empresa de Scribd logo
1 de 35
Moose




Sawyer X
Sawyer X
blogs.perl.org/users/sawyer_x
search.cpan.org/~xsawyerx
metacpan.org/author/XSAWYERX
github.com/xsawyerx/
„The Dancer guy!“
Projects: Dancer, Module::Starter, MetaCPAN::API,
 MooseX::Role::Loggable, etc.
Moose
Object system
Metaclass-based
Advanced
Sophisticated
Extensible
Production-ready
… but why Moose?
package Person;                                            package User;

use strict;                                                use Email::Valid;
use warnings;                                              use Moose;
                                                           use Moose::Util::TypeConstraints;
use Carp qw( confess );
use DateTime;                                              extends 'Person';
use DateTime::Format::Natural;
                                                           subtype 'Email'
                                                               => as 'Str'
sub new {                                                      => where { Email::Valid­>address($_) }
    my $class = shift;                                         => message { "$_ is not a valid email 
    my %p = ref $_[0] ? %{ $_[0] } : @_;                   address" };

    exists $p{name}                                        has email_address => (
        or confess 'name is a required attribute';             is       => 'rw',
    $class­>_validate_name( $p{name} );                        isa      => 'Email',
                                                               required => 1,
    exists $p{birth_date}                                  );
        or confess 'birth_date is a required attribute';

    $p{birth_date} = $class­
>_coerce_birth_date( $p{birth_date} );
    $class­>_validate_birth_date( $p{birth_date} );

    $p{shirt_size} = 'l'
        unless exists $p{shirt_size}:

    $class­>_validate_shirt_size( $p{shirt_size} );

    return bless %p, $class;
}

sub _validate_name {
    shift;
    my $name = shift;

    local $Carp::CarpLevel = $Carp::CarpLevel + 1;

    defined $name
        or confess 'name must be a string';
}
Get it?
Writing objects in basic Perl 5
Create a reference (usually to a hash)
Connect it to a package (using „bless“)
Provide subroutines that access the hash keys
Error check the hell out of it
Writing objects in basic Perl 5, e.g.
package Dog;
use strict; use warnings;
sub new {
     my $class = shift;
     my $self   = bless {}, $class;
     return $self;
}
1;
Issues
Defining the same new() concept every time
No parameters for new() yet
Will have to do all error-checking manually
Moose
package Dog;


use Moose;


1;
You get
use strict;
use warnings;
new() method
To hell with ponies, you get a moose!
(roll picture of a moose beating a pony in soccer)
Full affordance accessors (attributes)
has name => ( is => 'rw' );
„ro“ is available for read-only attributes
You can manually change setter/getter via writer/reader
Attributes can have defaults
Attributes can have type constraints
Attributes can have traits
Attributes can be lazy, have builders, clearers, predicates...
Type constraints
has name => ( is => 'ro', isa => 'Str' );
Str, Int, Bool, ArrayRef, HashRef, CodeRef, Regex,
 Classes
Combine: ArrayRef|HashRef, ArrayRef[Str]
Derivatives (Int is a Num)
Create your own using subtype, available at
 Moose::Util::TypeConstraints
Methods
Same as before
sub run {
      my $self = shift;
       say qq{I make it a habit only to run when
    being chased!};
}
Inheritance easy as...
package Punk
use Moose;
extends 'Person';
Multiple inheritance also possible (extends accepts array)
package Child;
use Moose;
extends qw/Father Mother/;
Roles are even better
package Punk;
use Moose;
with qw/Tattoos Piercings Squatter/;


Roles are things you do, instead of things you are.
More hooks than a coat rack!
package User::WinterAware;
use Moose;
extends 'User';
before leaving => sub {
  my $self = shift;
  $self->cold and $self->take_jacket;
};
More hooks than a coat rack!
package User::Secure;
use Moose;
extends 'User';
around login => sub {
  my $orig = shift;
  my $self = shift;
  $self->security_check and $self->$orig(@_);
};
More hooks than a coat rack!
Before
After
Around
Inner
Augment
Back to attributes...
has set => (
  is         => 'rw',
  isa        => 'Set::Object',
  default    => sub { Set::Object->new },
  required   => 1,
  lazy       => 1,
  predicate => 'has_set',
  clearer    => 'clear_set',
Attribute options: default
default => 'kitteh'                  # string
default => 3                         # number
default => sub { {} }                # HashRef
default => sub { [] }                # ArrayRef
default => sub { Object->new } # an Object


    (if you need a more elaborate sub, use builder)
Attribute options: required
required => 1 # required
required => 0 # not required
Attribute options: lazy
lazy => 1 # make it lazy


Class will not create the slot for this attribute unless it
absolutely has to, defined by whether it is accessed at all.


No access? No penalty!
Lazy == good
Attribute options: builder
builder => 'build_it' # subroutine name


sub build_it {
    my $self = shift; # not a problem!
  return Some::Object->new( $self-
>more_opts );
}
Attribute options: clearer
clearer => 'clear_it' # subroutine name


# you don't need to create the subroutine
sub time_machine {
    my $self = shift;
    $self->clear_it; # 'it' never happened :)
}
Attribute options: predicate
predicate => 'has_it' # subroutine name


# you don't need to create the subroutine
sub try_to_do_it {
    my $self = shift;
    $self->has_it && $self->do_it();
}
Attribute options: lazy_build
lazy_build => 1 # <3


# the same as:
lazy        => 1,
builder     => '_build_it', # private
clearer     => 'clear_it',
predicate => 'has_it',
Example: Comican
A hub for various comics strips
Allow you to fetch comic strips
Standard uniformed interface to add more comics
We'll be using:
  Roles
  Lazy attributes
  Overriding attributes options
  Attribute predicates
Comican
      comic modules        Comican::Comic::Dilber
                                     t              interface
                                                      role
       Comican::Comic::PennyArcade

Comican::Comic::xkcd                                 Comican::
                                                    Role::Comic

                          main module
   user


                             Comican.pm
Comican: overall
Comican.pm is the user's interface
It's a hub for Comican::Comic::* modules
They are objects that fetch specific comic strips
They have a common interface
Defined by Comican::Role::Comic
SHOW ME THE CODE!
/^M(?:o(?:o|[ou]se)?)?$/
Moose: standart
Mouse: subset, uses XS, faster
(Any::Moose: use Mouse unless Moose already loaded)
Moo: Pure-Perl, subset, blazing fast
Mo: As little as possible (incl. character count)
M: Really as little as possible
Hummus (HuMoose): Incompatible chickpeas paste
Thank you.

Más contenido relacionado

La actualidad más candente

Introduction To Moose
Introduction To MooseIntroduction To Moose
Introduction To MooseMike Whitaker
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScriptNone
 
Introduction to CoffeeScript
Introduction to CoffeeScriptIntroduction to CoffeeScript
Introduction to CoffeeScriptStalin Thangaraj
 
DBIx::Class beginners
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginnersleo lapworth
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010leo lapworth
 
Writing Friendly libraries for CodeIgniter
Writing Friendly libraries for CodeIgniterWriting Friendly libraries for CodeIgniter
Writing Friendly libraries for CodeIgniterCodeIgniter Conference
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Kris Wallsmith
 
Puppet Camp Paris 2015: Power of Puppet 4 (Beginner)
Puppet Camp Paris 2015: Power of Puppet 4 (Beginner) Puppet Camp Paris 2015: Power of Puppet 4 (Beginner)
Puppet Camp Paris 2015: Power of Puppet 4 (Beginner) Puppet
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In PerlKang-min Liu
 
LPW: Beginners Perl
LPW: Beginners PerlLPW: Beginners Perl
LPW: Beginners PerlDave Cross
 
WordPress Cuztom Helper
WordPress Cuztom HelperWordPress Cuztom Helper
WordPress Cuztom Helperslicejack
 
"The worst code I ever wrote"
"The worst code I ever wrote""The worst code I ever wrote"
"The worst code I ever wrote"Tomas Doran
 
Constructive Destructor Use
Constructive Destructor UseConstructive Destructor Use
Constructive Destructor Usemetaperl
 
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPMariano Iglesias
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl TechniquesDave Cross
 
Introduction to Perl Best Practices
Introduction to Perl Best PracticesIntroduction to Perl Best Practices
Introduction to Perl Best PracticesJosé Castro
 

La actualidad más candente (20)

Introduction To Moose
Introduction To MooseIntroduction To Moose
Introduction To Moose
 
CoffeeScript
CoffeeScriptCoffeeScript
CoffeeScript
 
Introduction to CoffeeScript
Introduction to CoffeeScriptIntroduction to CoffeeScript
Introduction to CoffeeScript
 
Coffee Script
Coffee ScriptCoffee Script
Coffee Script
 
DBIx::Class beginners
DBIx::Class beginnersDBIx::Class beginners
DBIx::Class beginners
 
DBIx::Class introduction - 2010
DBIx::Class introduction - 2010DBIx::Class introduction - 2010
DBIx::Class introduction - 2010
 
Writing Friendly libraries for CodeIgniter
Writing Friendly libraries for CodeIgniterWriting Friendly libraries for CodeIgniter
Writing Friendly libraries for CodeIgniter
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
 
Puppet Camp Paris 2015: Power of Puppet 4 (Beginner)
Puppet Camp Paris 2015: Power of Puppet 4 (Beginner) Puppet Camp Paris 2015: Power of Puppet 4 (Beginner)
Puppet Camp Paris 2015: Power of Puppet 4 (Beginner)
 
Power of Puppet 4
Power of Puppet 4Power of Puppet 4
Power of Puppet 4
 
Good Evils In Perl
Good Evils In PerlGood Evils In Perl
Good Evils In Perl
 
LPW: Beginners Perl
LPW: Beginners PerlLPW: Beginners Perl
LPW: Beginners Perl
 
WordPress Cuztom Helper
WordPress Cuztom HelperWordPress Cuztom Helper
WordPress Cuztom Helper
 
"The worst code I ever wrote"
"The worst code I ever wrote""The worst code I ever wrote"
"The worst code I ever wrote"
 
Constructive Destructor Use
Constructive Destructor UseConstructive Destructor Use
Constructive Destructor Use
 
Perl
PerlPerl
Perl
 
Going crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHPGoing crazy with Node.JS and CakePHP
Going crazy with Node.JS and CakePHP
 
Advanced Perl Techniques
Advanced Perl TechniquesAdvanced Perl Techniques
Advanced Perl Techniques
 
Introduction to Perl Best Practices
Introduction to Perl Best PracticesIntroduction to Perl Best Practices
Introduction to Perl Best Practices
 
Your JavaScript Library
Your JavaScript LibraryYour JavaScript Library
Your JavaScript Library
 

Destacado

Java. Lecture 03. OOP and UML
Java. Lecture 03. OOP and UMLJava. Lecture 03. OOP and UML
Java. Lecture 03. OOP and UMLcolriot
 
A very nice presentation on Moose.
A very nice presentation on Moose.A very nice presentation on Moose.
A very nice presentation on Moose.Chankey Pathak
 
Moose workshop
Moose workshopMoose workshop
Moose workshopYnon Perek
 
Firewall in Perl by Chankey Pathak
Firewall in Perl by Chankey PathakFirewall in Perl by Chankey Pathak
Firewall in Perl by Chankey PathakChankey Pathak
 
Moose Hacking Guide
Moose Hacking GuideMoose Hacking Guide
Moose Hacking Guideguest6b8f09
 
Introduction to Perl MAGIC
Introduction to Perl MAGICIntroduction to Perl MAGIC
Introduction to Perl MAGICguest6b8f09
 
Introduction to OO Perl with Moose
Introduction to OO Perl with MooseIntroduction to OO Perl with Moose
Introduction to OO Perl with MooseDave Cross
 
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情Junichi Ishida
 
Great Tools Heavily Used In Japan, You Don't Know.
Great Tools Heavily Used In Japan, You Don't Know.Great Tools Heavily Used In Japan, You Don't Know.
Great Tools Heavily Used In Japan, You Don't Know.Junichi Ishida
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.VimLin Yo-An
 
10 books that every developer must read
10 books that every developer must read10 books that every developer must read
10 books that every developer must readGanesh Samarthyam
 

Destacado (12)

Java. Lecture 03. OOP and UML
Java. Lecture 03. OOP and UMLJava. Lecture 03. OOP and UML
Java. Lecture 03. OOP and UML
 
A very nice presentation on Moose.
A very nice presentation on Moose.A very nice presentation on Moose.
A very nice presentation on Moose.
 
Moose workshop
Moose workshopMoose workshop
Moose workshop
 
Firewall in Perl by Chankey Pathak
Firewall in Perl by Chankey PathakFirewall in Perl by Chankey Pathak
Firewall in Perl by Chankey Pathak
 
Moose Hacking Guide
Moose Hacking GuideMoose Hacking Guide
Moose Hacking Guide
 
Introduction to Perl MAGIC
Introduction to Perl MAGICIntroduction to Perl MAGIC
Introduction to Perl MAGIC
 
Introduction to OO Perl with Moose
Introduction to OO Perl with MooseIntroduction to OO Perl with Moose
Introduction to OO Perl with Moose
 
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情
YAPC::Asia 2014 - 半端なPHPDisでPHPerに陰で笑われないためのPerl Monger向け最新PHP事情
 
Great Tools Heavily Used In Japan, You Don't Know.
Great Tools Heavily Used In Japan, You Don't Know.Great Tools Heavily Used In Japan, You Don't Know.
Great Tools Heavily Used In Japan, You Don't Know.
 
Perl.Hacks.On.Vim
Perl.Hacks.On.VimPerl.Hacks.On.Vim
Perl.Hacks.On.Vim
 
10 books that every developer must read
10 books that every developer must read10 books that every developer must read
10 books that every developer must read
 
The Programmer
The ProgrammerThe Programmer
The Programmer
 

Similar a Moose - YAPC::NA 2012

Perl: Hate it for the Right Reasons
Perl: Hate it for the Right ReasonsPerl: Hate it for the Right Reasons
Perl: Hate it for the Right ReasonsMatt Follett
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksNate Abele
 
Moose: Perl Objects
Moose: Perl ObjectsMoose: Perl Objects
Moose: Perl ObjectsLambert Lum
 
To infinity and beyond
To infinity and beyondTo infinity and beyond
To infinity and beyondclintongormley
 
(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Rolessartak
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Kang-min Liu
 
Puppet and the HashiStack
Puppet and the HashiStackPuppet and the HashiStack
Puppet and the HashiStackBram Vogelaar
 
Perl Teach-In (part 2)
Perl Teach-In (part 2)Perl Teach-In (part 2)
Perl Teach-In (part 2)Dave Cross
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Puppet
 
Replacing "exec" with a type and provider
Replacing "exec" with a type and providerReplacing "exec" with a type and provider
Replacing "exec" with a type and providerDominic Cleal
 
Stanford Hackathon - Puppet Modules
Stanford Hackathon - Puppet ModulesStanford Hackathon - Puppet Modules
Stanford Hackathon - Puppet ModulesPuppet
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Railselliando dias
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v RubyJano Suchal
 
Reasons To Love Ruby
Reasons To Love RubyReasons To Love Ruby
Reasons To Love RubyBen Scheirman
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming LanguageDuda Dornelles
 
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesA linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesTchelinux
 
jRuby: The best of both worlds
jRuby: The best of both worldsjRuby: The best of both worlds
jRuby: The best of both worldsChristopher Spring
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 

Similar a Moose - YAPC::NA 2012 (20)

Perl object ?
Perl object ?Perl object ?
Perl object ?
 
Perl: Hate it for the Right Reasons
Perl: Hate it for the Right ReasonsPerl: Hate it for the Right Reasons
Perl: Hate it for the Right Reasons
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
Moose: Perl Objects
Moose: Perl ObjectsMoose: Perl Objects
Moose: Perl Objects
 
To infinity and beyond
To infinity and beyondTo infinity and beyond
To infinity and beyond
 
(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Roles
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Puppet and the HashiStack
Puppet and the HashiStackPuppet and the HashiStack
Puppet and the HashiStack
 
Perl Teach-In (part 2)
Perl Teach-In (part 2)Perl Teach-In (part 2)
Perl Teach-In (part 2)
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...
 
Replacing "exec" with a type and provider
Replacing "exec" with a type and providerReplacing "exec" with a type and provider
Replacing "exec" with a type and provider
 
Stanford Hackathon - Puppet Modules
Stanford Hackathon - Puppet ModulesStanford Hackathon - Puppet Modules
Stanford Hackathon - Puppet Modules
 
Rapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and RailsRapid Development with Ruby/JRuby and Rails
Rapid Development with Ruby/JRuby and Rails
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
Reasons To Love Ruby
Reasons To Love RubyReasons To Love Ruby
Reasons To Love Ruby
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
 
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesA linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
 
jRuby: The best of both worlds
jRuby: The best of both worldsjRuby: The best of both worlds
jRuby: The best of both worlds
 
DataMapper
DataMapperDataMapper
DataMapper
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 

Más de xSawyer

do_this and die();
do_this and die();do_this and die();
do_this and die();xSawyer
 
Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)xSawyer
 
Asynchronous programming FTW!
Asynchronous programming FTW!Asynchronous programming FTW!
Asynchronous programming FTW!xSawyer
 
Our local state, my, my - Understanding Perl variables
Our local state, my, my - Understanding Perl variablesOur local state, my, my - Understanding Perl variables
Our local state, my, my - Understanding Perl variablesxSawyer
 
Your first website in under a minute with Dancer
Your first website in under a minute with DancerYour first website in under a minute with Dancer
Your first website in under a minute with DancerxSawyer
 
PerlDancer for Perlers (FOSDEM 2011)
PerlDancer for Perlers (FOSDEM 2011)PerlDancer for Perlers (FOSDEM 2011)
PerlDancer for Perlers (FOSDEM 2011)xSawyer
 
Perl Dancer for Python programmers
Perl Dancer for Python programmersPerl Dancer for Python programmers
Perl Dancer for Python programmersxSawyer
 
When Perl Met Android (YAPC::EU 2010)
When Perl Met Android (YAPC::EU 2010)When Perl Met Android (YAPC::EU 2010)
When Perl Met Android (YAPC::EU 2010)xSawyer
 
Perl Dancer on Android (first attempt)
Perl Dancer on Android (first attempt)Perl Dancer on Android (first attempt)
Perl Dancer on Android (first attempt)xSawyer
 
Source Code Management systems
Source Code Management systemsSource Code Management systems
Source Code Management systemsxSawyer
 
Red Flags in Programming
Red Flags in ProgrammingRed Flags in Programming
Red Flags in ProgrammingxSawyer
 

Más de xSawyer (12)

do_this and die();
do_this and die();do_this and die();
do_this and die();
 
XS Fun
XS FunXS Fun
XS Fun
 
Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)Asynchronous Programming FTW! 2 (with AnyEvent)
Asynchronous Programming FTW! 2 (with AnyEvent)
 
Asynchronous programming FTW!
Asynchronous programming FTW!Asynchronous programming FTW!
Asynchronous programming FTW!
 
Our local state, my, my - Understanding Perl variables
Our local state, my, my - Understanding Perl variablesOur local state, my, my - Understanding Perl variables
Our local state, my, my - Understanding Perl variables
 
Your first website in under a minute with Dancer
Your first website in under a minute with DancerYour first website in under a minute with Dancer
Your first website in under a minute with Dancer
 
PerlDancer for Perlers (FOSDEM 2011)
PerlDancer for Perlers (FOSDEM 2011)PerlDancer for Perlers (FOSDEM 2011)
PerlDancer for Perlers (FOSDEM 2011)
 
Perl Dancer for Python programmers
Perl Dancer for Python programmersPerl Dancer for Python programmers
Perl Dancer for Python programmers
 
When Perl Met Android (YAPC::EU 2010)
When Perl Met Android (YAPC::EU 2010)When Perl Met Android (YAPC::EU 2010)
When Perl Met Android (YAPC::EU 2010)
 
Perl Dancer on Android (first attempt)
Perl Dancer on Android (first attempt)Perl Dancer on Android (first attempt)
Perl Dancer on Android (first attempt)
 
Source Code Management systems
Source Code Management systemsSource Code Management systems
Source Code Management systems
 
Red Flags in Programming
Red Flags in ProgrammingRed Flags in Programming
Red Flags in Programming
 

Último

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 

Último (20)

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 

Moose - YAPC::NA 2012

  • 2. Sawyer X blogs.perl.org/users/sawyer_x search.cpan.org/~xsawyerx metacpan.org/author/XSAWYERX github.com/xsawyerx/ „The Dancer guy!“ Projects: Dancer, Module::Starter, MetaCPAN::API, MooseX::Role::Loggable, etc.
  • 3.
  • 4.
  • 6. … but why Moose? package Person; package User; use strict; use Email::Valid; use warnings; use Moose; use Moose::Util::TypeConstraints; use Carp qw( confess ); use DateTime; extends 'Person'; use DateTime::Format::Natural; subtype 'Email'     => as 'Str' sub new {     => where { Email::Valid­>address($_) }     my $class = shift;     => message { "$_ is not a valid email      my %p = ref $_[0] ? %{ $_[0] } : @_; address" };     exists $p{name} has email_address => (         or confess 'name is a required attribute';     is       => 'rw',     $class­>_validate_name( $p{name} );     isa      => 'Email',     required => 1,     exists $p{birth_date} );         or confess 'birth_date is a required attribute';     $p{birth_date} = $class­ >_coerce_birth_date( $p{birth_date} );     $class­>_validate_birth_date( $p{birth_date} );     $p{shirt_size} = 'l'         unless exists $p{shirt_size}:     $class­>_validate_shirt_size( $p{shirt_size} );     return bless %p, $class; } sub _validate_name {     shift;     my $name = shift;     local $Carp::CarpLevel = $Carp::CarpLevel + 1;     defined $name         or confess 'name must be a string'; }
  • 8. Writing objects in basic Perl 5 Create a reference (usually to a hash) Connect it to a package (using „bless“) Provide subroutines that access the hash keys Error check the hell out of it
  • 9. Writing objects in basic Perl 5, e.g. package Dog; use strict; use warnings; sub new { my $class = shift; my $self = bless {}, $class; return $self; } 1;
  • 10. Issues Defining the same new() concept every time No parameters for new() yet Will have to do all error-checking manually
  • 12. You get use strict; use warnings; new() method To hell with ponies, you get a moose! (roll picture of a moose beating a pony in soccer)
  • 13. Full affordance accessors (attributes) has name => ( is => 'rw' ); „ro“ is available for read-only attributes You can manually change setter/getter via writer/reader Attributes can have defaults Attributes can have type constraints Attributes can have traits Attributes can be lazy, have builders, clearers, predicates...
  • 14. Type constraints has name => ( is => 'ro', isa => 'Str' ); Str, Int, Bool, ArrayRef, HashRef, CodeRef, Regex, Classes Combine: ArrayRef|HashRef, ArrayRef[Str] Derivatives (Int is a Num) Create your own using subtype, available at Moose::Util::TypeConstraints
  • 15. Methods Same as before sub run { my $self = shift; say qq{I make it a habit only to run when being chased!}; }
  • 16. Inheritance easy as... package Punk use Moose; extends 'Person'; Multiple inheritance also possible (extends accepts array) package Child; use Moose; extends qw/Father Mother/;
  • 17. Roles are even better package Punk; use Moose; with qw/Tattoos Piercings Squatter/; Roles are things you do, instead of things you are.
  • 18. More hooks than a coat rack! package User::WinterAware; use Moose; extends 'User'; before leaving => sub { my $self = shift; $self->cold and $self->take_jacket; };
  • 19. More hooks than a coat rack! package User::Secure; use Moose; extends 'User'; around login => sub { my $orig = shift; my $self = shift; $self->security_check and $self->$orig(@_); };
  • 20. More hooks than a coat rack! Before After Around Inner Augment
  • 21. Back to attributes... has set => ( is => 'rw', isa => 'Set::Object', default => sub { Set::Object->new }, required => 1, lazy => 1, predicate => 'has_set', clearer => 'clear_set',
  • 22. Attribute options: default default => 'kitteh' # string default => 3 # number default => sub { {} } # HashRef default => sub { [] } # ArrayRef default => sub { Object->new } # an Object (if you need a more elaborate sub, use builder)
  • 23. Attribute options: required required => 1 # required required => 0 # not required
  • 24. Attribute options: lazy lazy => 1 # make it lazy Class will not create the slot for this attribute unless it absolutely has to, defined by whether it is accessed at all. No access? No penalty! Lazy == good
  • 25. Attribute options: builder builder => 'build_it' # subroutine name sub build_it { my $self = shift; # not a problem! return Some::Object->new( $self- >more_opts ); }
  • 26. Attribute options: clearer clearer => 'clear_it' # subroutine name # you don't need to create the subroutine sub time_machine { my $self = shift; $self->clear_it; # 'it' never happened :) }
  • 27. Attribute options: predicate predicate => 'has_it' # subroutine name # you don't need to create the subroutine sub try_to_do_it { my $self = shift; $self->has_it && $self->do_it(); }
  • 28. Attribute options: lazy_build lazy_build => 1 # <3 # the same as: lazy => 1, builder => '_build_it', # private clearer => 'clear_it', predicate => 'has_it',
  • 29. Example: Comican A hub for various comics strips Allow you to fetch comic strips Standard uniformed interface to add more comics We'll be using: Roles Lazy attributes Overriding attributes options Attribute predicates
  • 30. Comican comic modules Comican::Comic::Dilber t interface role Comican::Comic::PennyArcade Comican::Comic::xkcd Comican:: Role::Comic main module user Comican.pm
  • 31. Comican: overall Comican.pm is the user's interface It's a hub for Comican::Comic::* modules They are objects that fetch specific comic strips They have a common interface Defined by Comican::Role::Comic
  • 32. SHOW ME THE CODE!
  • 33. /^M(?:o(?:o|[ou]se)?)?$/ Moose: standart Mouse: subset, uses XS, faster (Any::Moose: use Mouse unless Moose already loaded) Moo: Pure-Perl, subset, blazing fast Mo: As little as possible (incl. character count) M: Really as little as possible Hummus (HuMoose): Incompatible chickpeas paste
  • 34.