ÿØÿà JFIF    ÿÛ „ ( %!1!%*+...983,7(-.- Method/Modifiers.pm000044400000041225152346200270010246 0ustar00use strict; use warnings; package Class::Method::Modifiers; # git description: v2.14-6-gede37cf # ABSTRACT: Provides Moose-like method modifiers # KEYWORDS: method wrap modification patch # vim: set ts=8 sts=4 sw=4 tw=115 et : our $VERSION = '2.15'; use base 'Exporter'; our @EXPORT = qw(before after around); our @EXPORT_OK = (@EXPORT, qw(fresh install_modifier)); our %EXPORT_TAGS = ( moose => [qw(before after around)], all => \@EXPORT_OK, ); BEGIN { *_HAS_READONLY = $] >= 5.008 ? sub(){1} : sub(){0}; } our %MODIFIER_CACHE; # for backward compatibility sub _install_modifier; # -w *_install_modifier = \&install_modifier; sub install_modifier { my $into = shift; my $type = shift; my $code = pop; my @names = @_; @names = @{ $names[0] } if ref($names[0]) eq 'ARRAY'; return _fresh($into, $code, @names) if $type eq 'fresh'; for my $name (@names) { my $hit = $into->can($name) or do { require Carp; Carp::confess("The method '$name' is not found in the inheritance hierarchy for class $into"); }; my $qualified = $into.'::'.$name; my $cache = $MODIFIER_CACHE{$into}{$name} ||= { before => [], after => [], around => [], }; # this must be the first modifier we're installing if (!exists($cache->{"orig"})) { no strict 'refs'; # grab the original method (or undef if the method is inherited) $cache->{"orig"} = *{$qualified}{CODE}; # the "innermost" method, the one that "around" will ultimately wrap $cache->{"wrapped"} = $cache->{"orig"} || $hit; #sub { # # we can't cache this, because new methods or modifiers may be # # added between now and when this method is called # for my $package (@{ mro::get_linear_isa($into) }) { # next if $package eq $into; # my $code = *{$package.'::'.$name}{CODE}; # goto $code if $code; # } # require Carp; # Carp::confess("$qualified\::$name disappeared?"); #}; } # keep these lists in the order the modifiers are called if ($type eq 'after') { push @{ $cache->{$type} }, $code; } else { unshift @{ $cache->{$type} }, $code; } # wrap the method with another layer of around. much simpler than # the Moose equivalent. :) if ($type eq 'around') { my $method = $cache->{wrapped}; my $attrs = _sub_attrs($code); # a bare "sub :lvalue {...}" will be parsed as a label and an # indirect method call. force it to be treated as an expression # using + $cache->{wrapped} = eval "package $into; +sub $attrs { \$code->(\$method, \@_); };"; } # install our new method which dispatches the modifiers, but only # if a new type was added if (@{ $cache->{$type} } == 1) { # avoid these hash lookups every method invocation my $before = $cache->{"before"}; my $after = $cache->{"after"}; # this is a coderef that changes every new "around". so we need # to take a reference to it. better a deref than a hash lookup my $wrapped = \$cache->{"wrapped"}; my $attrs = _sub_attrs($cache->{wrapped}); my $generated = "package $into;\n"; $generated .= "sub $name $attrs {"; # before is easy, it doesn't affect the return value(s) if (@$before) { $generated .= ' for my $method (@$before) { $method->(@_); } '; } if (@$after) { $generated .= ' my $ret; if (wantarray) { $ret = [$$wrapped->(@_)]; '.(_HAS_READONLY ? 'Internals::SvREADONLY(@$ret, 1);' : '').' } elsif (defined wantarray) { $ret = \($$wrapped->(@_)); } else { $$wrapped->(@_); } for my $method (@$after) { $method->(@_); } wantarray ? @$ret : $ret ? $$ret : (); ' } else { $generated .= '$$wrapped->(@_);'; } $generated .= '}'; no strict 'refs'; no warnings 'redefine'; no warnings 'closure'; eval $generated; }; } } sub before { _install_modifier(scalar(caller), 'before', @_); } sub after { _install_modifier(scalar(caller), 'after', @_); } sub around { _install_modifier(scalar(caller), 'around', @_); } sub fresh { my $code = pop; my @names = @_; @names = @{ $names[0] } if ref($names[0]) eq 'ARRAY'; _fresh(scalar(caller), $code, @names); } sub _fresh { my ($into, $code, @names) = @_; for my $name (@names) { if ($name !~ /\A [a-zA-Z_] [a-zA-Z0-9_]* \z/xms) { require Carp; Carp::confess("Invalid method name '$name'"); } if ($into->can($name)) { require Carp; Carp::confess("Class $into already has a method named '$name'"); } # We need to make sure that the installed method has its CvNAME in # the appropriate package; otherwise, it would be subject to # deletion if callers use namespace::autoclean. If $code was # compiled in the target package, we can just install it directly; # otherwise, we'll need a different approach. Using Sub::Name would # be fine in all cases, at the cost of introducing a dependency on # an XS-using, non-core module. So instead we'll use string-eval to # create a new subroutine that wraps $code. if (_is_in_package($code, $into)) { no strict 'refs'; *{"$into\::$name"} = $code; } else { no warnings 'closure'; # for 5.8.x my $attrs = _sub_attrs($code); eval "package $into; sub $name $attrs { \$code->(\@_) }"; } } } sub _sub_attrs { my ($coderef) = @_; local *_sub = $coderef; local $@; local $SIG{__DIE__}; # this assignment will fail to compile if it isn't an lvalue sub. we # never want to actually call the sub though, so we return early. (eval 'return 1; &_sub = 1') ? ':lvalue' : ''; } sub _is_in_package { my ($coderef, $package) = @_; require B; my $cv = B::svref_2object($coderef); return $cv->GV->STASH->NAME eq $package; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Class::Method::Modifiers - Provides Moose-like method modifiers =head1 VERSION version 2.15 =head1 SYNOPSIS package Child; use parent 'MyParent'; use Class::Method::Modifiers; sub new_method { } before 'old_method' => sub { carp "old_method is deprecated, use new_method"; }; around 'other_method' => sub { my $orig = shift; my $ret = $orig->(@_); return $ret =~ /\d/ ? $ret : lc $ret; }; after 'private', 'protected' => sub { debug "finished calling a dangerous method"; }; use Class::Method::Modifiers qw(fresh); fresh 'not_in_hierarchy' => sub { warn "freshly added method\n"; }; =head1 DESCRIPTION =for stopwords CLOS Method modifiers are a convenient feature from the CLOS (Common Lisp Object System) world. In its most basic form, a method modifier is just a method that calls C<< $self->SUPER::foo(@_) >>. I for one have trouble remembering that exact invocation, so my classes seldom re-dispatch to their base classes. Very bad! C provides three modifiers: C, C, and C. C and C are run just before and after the method they modify, but can not really affect that original method. C is run in place of the original method, with a hook to easily call that original method. See the L section for more details on how the particular modifiers work. One clear benefit of using C is that you can define multiple modifiers in a single namespace. These separate modifiers don't need to know about each other. This makes top-down design easy. Have a base class that provides the skeleton methods of each operation, and have plugins modify those methods to flesh out the specifics. Parent classes need not know about C. This means you should be able to modify methods in I subclass. See L for an example of subclassing with C. In short, C solves the problem of making sure you call C<< $self->SUPER::foo(@_) >>, and provides a cleaner interface for it. As of version 1.00, C is faster in some cases than L. See F in the L distribution. C also provides an additional "modifier" type, C; see below. =head1 MODIFIERS All modifiers let you modify one or multiple methods at a time. The names of multiple methods can be provided as a list or as an array-reference. Examples: before 'method' => sub { ... }; before 'method1', 'method2' => sub { ... }; before [ 'method1', 'method2' ] => sub { ... }; =head2 before method(s) => sub { ... }; C is called before the method it is modifying. Its return value is totally ignored. It receives the same C<@_> as the method it is modifying would have received. You can modify the C<@_> the original method will receive by changing C<$_[0]> and friends (or by changing anything inside a reference). This is a feature! =head2 after method(s) => sub { ... }; C is called after the method it is modifying. Its return value is totally ignored. It receives the same C<@_> as the method it is modifying received, mostly. The original method can modify C<@_> (such as by changing C<$_[0]> or references) and C will see the modified version. If you don't like this behavior, specify both a C and C, and copy the C<@_> during C for C to use. =head2 around method(s) => sub { ... }; C is called instead of the method it is modifying. The method you're overriding is passed in as the first argument (called C<$orig> by convention). Watch out for contextual return values of C<$orig>. You can use C to: =over 4 =item Pass C<$orig> a different C<@_> around 'method' => sub { my $orig = shift; my $self = shift; $orig->($self, reverse @_); }; =item Munge the return value of C<$orig> around 'method' => sub { my $orig = shift; ucfirst $orig->(@_); }; =item Avoid calling C<$orig> -- conditionally around 'method' => sub { my $orig = shift; return $orig->(@_) if time() % 2; return "no dice, captain"; }; =back =head2 fresh method(s) => sub { ... }; (Available since version 2.00) Unlike the other modifiers, this does not modify an existing method. Ordinarily, C merely installs the coderef as a method in the appropriate class; but if the class hierarchy already contains a method of the same name, an exception is thrown. The idea of this "modifier" is to increase safety when subclassing. Suppose you're writing a subclass of a class Some::Base, and adding a new method: package My::Subclass; use base 'Some::Base'; sub foo { ... } If a later version of Some::Base also adds a new method named C, your method will shadow that method. Alternatively, you can use C to install the additional method into your subclass: package My::Subclass; use base 'Some::Base'; use Class::Method::Modifiers 'fresh'; fresh 'foo' => sub { ... }; Now upgrading Some::Base to a version with a conflicting C method will cause an exception to be thrown; seeing that error will give you the opportunity to fix the problem (perhaps by picking a different method name in your subclass, or similar). Creating fresh methods with C (see below) provides a way to get similar safety benefits when adding local monkeypatches to existing classes; see L. For API compatibility reasons, this function is exported only when you ask for it specifically, or for C<:all>. =head2 install_modifier $package, $type, @names, sub { ... } C is like C, C, C, and C but it also lets you dynamically select the modifier type ('before', 'after', 'around', 'fresh') and package that the method modifiers are installed into. This expert-level function is exported only when you ask for it specifically, or for C<:all>. =head1 NOTES All three normal modifiers; C, C, and C; are exported into your namespace by default. You may C to avoid modifying your namespace. I may steal more features from L, namely C, C, C, C, and whatever the L folks come up with next. Note that the syntax and semantics for these modifiers is directly borrowed from L (the implementations, however, are not). L shares a few similarities with C, and they even have some overlap in purpose -- both can be used to implement highly pluggable applications. The difference is that L provides a mechanism for easily letting parent classes to invoke hooks defined by other code. C provides a way of overriding/augmenting methods safely, and the parent class need not know about it. =head2 :lvalue METHODS When adding C or C modifiers, the wrapper method will be an lvalue method if the wrapped sub is, and assigning to the method will propagate to the wrapped method as expected. For C modifiers, it is the modifier sub that determines if the wrapper method is an lvalue method. =head1 CAVEATS It is erroneous to modify a method that doesn't exist in your class's inheritance hierarchy. If this occurs, an exception will be thrown when the modifier is defined. It doesn't yet play well with C. There are some C tests for this. Don't get your hopes up though! Applying modifiers to array lvalue methods is not fully supported. Attempting to assign to an array lvalue method that has an C modifier applied will result in an error. Array lvalue methods are not well supported by perl in general, and should be avoided. =head1 MAJOR VERSION CHANGES =for stopwords reimplementation This module was bumped to 1.00 following a complete reimplementation, to indicate breaking backwards compatibility. The "guard" modifier was removed, and the internals are completely different. The new version is a few times faster with half the code. It's now even faster than Moose. Any code that just used modifiers should not change in behavior, except to become more correct. And, of course, faster. :) =head1 SEE ALSO =over 4 =item * L =item * L =item * L =item * L =item * L =item * L =back =head1 ACKNOWLEDGMENTS =for stopwords Stevan Thanks to Stevan Little for L, I would never have known about method modifiers otherwise. Thanks to Matt Trout and Stevan Little for their advice. =head1 SUPPORT Bugs may be submitted through L (or L). =head1 AUTHOR Shawn M Moore =head1 CONTRIBUTORS =for stopwords Karen Etheridge Shawn M Moore Graham Knop Aaron Crane Peter Rabbitson David Steinbrunner gfx Justin Hunter mannih Yves Orton =over 4 =item * Karen Etheridge =item * Shawn M Moore =item * Graham Knop =item * Aaron Crane =item * Peter Rabbitson =item * David Steinbrunner =item * gfx =item * Justin Hunter =item * mannih =item * Yves Orton =back =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2007 by Shawn M Moore. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut Tiny.pm000044400000041743152346200270006035 0ustar00use 5.006; use strict; no strict 'refs'; use warnings; package Class::Tiny; # ABSTRACT: Minimalist class construction our $VERSION = '1.008'; use Carp (); # load as .pm to hide from min version scanners require( $] >= 5.010 ? "mro.pm" : "MRO/Compat.pm" ); ## no critic: my %CLASS_ATTRIBUTES; sub import { my $class = shift; my $pkg = caller; $class->prepare_class($pkg); $class->create_attributes( $pkg, @_ ) if @_; } sub prepare_class { my ( $class, $pkg ) = @_; @{"${pkg}::ISA"} = "Class::Tiny::Object" unless @{"${pkg}::ISA"}; } # adapted from Object::Tiny and Object::Tiny::RW sub create_attributes { my ( $class, $pkg, @spec ) = @_; my %defaults = map { ref $_ eq 'HASH' ? %$_ : ( $_ => undef ) } @spec; my @attr = grep { defined and !ref and /^[^\W\d]\w*$/s or Carp::croak "Invalid accessor name '$_'" } keys %defaults; $CLASS_ATTRIBUTES{$pkg}{$_} = $defaults{$_} for @attr; $class->_gen_accessor( $pkg, $_ ) for grep { !*{"$pkg\::$_"}{CODE} } @attr; Carp::croak("Failed to generate attributes for $pkg: $@\n") if $@; } sub _gen_accessor { my ( $class, $pkg, $name ) = @_; my $outer_default = $CLASS_ATTRIBUTES{$pkg}{$name}; my $sub = $class->__gen_sub_body( $name, defined($outer_default), ref($outer_default) ); # default = outer_default avoids "won't stay shared" bug eval "package $pkg; my \$default=\$outer_default; $sub"; ## no critic Carp::croak("Failed to generate attributes for $pkg: $@\n") if $@; } # NOTE: overriding __gen_sub_body in a subclass of Class::Tiny is risky and # could break if the internals of Class::Tiny need to change for any # reason. That said, I currently see no reason why this would be likely to # change. # # The generated sub body should assume that a '$default' variable will be # in scope (i.e. when the sub is evaluated) with any default value/coderef sub __gen_sub_body { my ( $self, $name, $has_default, $default_type ) = @_; if ( $has_default && $default_type eq 'CODE' ) { return << "HERE"; sub $name { return ( ( \@_ == 1 && exists \$_[0]{$name} ) ? ( \$_[0]{$name} ) : ( \$_[0]{$name} = ( \@_ == 2 ) ? \$_[1] : \$default->( \$_[0] ) ) ); } HERE } elsif ($has_default) { return << "HERE"; sub $name { return ( ( \@_ == 1 && exists \$_[0]{$name} ) ? ( \$_[0]{$name} ) : ( \$_[0]{$name} = ( \@_ == 2 ) ? \$_[1] : \$default ) ); } HERE } else { return << "HERE"; sub $name { return \@_ == 1 ? \$_[0]{$name} : ( \$_[0]{$name} = \$_[1] ); } HERE } } sub get_all_attributes_for { my ( $class, $pkg ) = @_; my %attr = map { $_ => undef } map { keys %{ $CLASS_ATTRIBUTES{$_} || {} } } @{ mro::get_linear_isa($pkg) }; return keys %attr; } sub get_all_attribute_defaults_for { my ( $class, $pkg ) = @_; my $defaults = {}; for my $p ( reverse @{ mro::get_linear_isa($pkg) } ) { while ( my ( $k, $v ) = each %{ $CLASS_ATTRIBUTES{$p} || {} } ) { $defaults->{$k} = $v; } } return $defaults; } package Class::Tiny::Object; # ABSTRACT: Base class for classes built with Class::Tiny our $VERSION = '1.008'; my ( %HAS_BUILDARGS, %BUILD_CACHE, %DEMOLISH_CACHE, %ATTR_CACHE ); my $_PRECACHE = sub { no warnings 'once'; # needed to avoid downstream warnings my ($class) = @_; my $linear_isa = @{"$class\::ISA"} == 1 && ${"$class\::ISA"}[0] eq "Class::Tiny::Object" ? [$class] : mro::get_linear_isa($class); $DEMOLISH_CACHE{$class} = [ map { ( *{$_}{CODE} ) ? ( *{$_}{CODE} ) : () } map { "$_\::DEMOLISH" } @$linear_isa ]; $BUILD_CACHE{$class} = [ map { ( *{$_}{CODE} ) ? ( *{$_}{CODE} ) : () } map { "$_\::BUILD" } reverse @$linear_isa ]; $HAS_BUILDARGS{$class} = $class->can("BUILDARGS"); return $ATTR_CACHE{$class} = { map { $_ => 1 } Class::Tiny->get_all_attributes_for($class) }; }; sub new { my $class = shift; my $valid_attrs = $ATTR_CACHE{$class} || $_PRECACHE->($class); # handle hash ref or key/value arguments my $args; if ( $HAS_BUILDARGS{$class} ) { $args = $class->BUILDARGS(@_); } else { if ( @_ == 1 && ref $_[0] ) { my %copy = eval { %{ $_[0] } }; # try shallow copy Carp::croak("Argument to $class->new() could not be dereferenced as a hash") if $@; $args = \%copy; } elsif ( @_ % 2 == 0 ) { $args = {@_}; } else { Carp::croak("$class->new() got an odd number of elements"); } } # create object and invoke BUILD (unless we were given __no_BUILD__) my $self = bless { map { $_ => $args->{$_} } grep { exists $valid_attrs->{$_} } keys %$args }, $class; $self->BUILDALL($args) if !delete $args->{__no_BUILD__} && @{ $BUILD_CACHE{$class} }; return $self; } sub BUILDALL { $_->(@_) for @{ $BUILD_CACHE{ ref $_[0] } } } # Adapted from Moo and its dependencies require Devel::GlobalDestruction unless defined ${^GLOBAL_PHASE}; sub DESTROY { my $self = shift; my $class = ref $self; my $in_global_destruction = defined ${^GLOBAL_PHASE} ? ${^GLOBAL_PHASE} eq 'DESTRUCT' : Devel::GlobalDestruction::in_global_destruction(); for my $demolisher ( @{ $DEMOLISH_CACHE{$class} } ) { my $e = do { local ( $?, $@ ); eval { $demolisher->( $self, $in_global_destruction ) }; $@; }; no warnings 'misc'; # avoid (in cleanup) warnings die $e if $e; # rethrow } } 1; # vim: ts=4 sts=4 sw=4 et: __END__ =pod =encoding UTF-8 =head1 NAME Class::Tiny - Minimalist class construction =head1 VERSION version 1.008 =head1 SYNOPSIS In F: package Person; use Class::Tiny qw( name ); 1; In F: package Employee; use parent 'Person'; use Class::Tiny qw( ssn ), { timestamp => sub { time } # attribute with default }; 1; In F: use Employee; my $obj = Employee->new( name => "Larry", ssn => "111-22-3333" ); # unknown attributes are ignored my $obj = Employee->new( name => "Larry", OS => "Linux" ); # $obj->{OS} does not exist =head1 DESCRIPTION This module offers a minimalist class construction kit in around 120 lines of code. Here is a list of features: =over 4 =item * defines attributes via import arguments =item * generates read-write accessors =item * supports lazy attribute defaults =item * supports custom accessors =item * superclass provides a standard C constructor =item * C takes a hash reference or list of key/value pairs =item * C supports providing C to customize constructor options =item * C calls C for each class from parent to child =item * superclass provides a C method =item * C calls C for each class from child to parent =back Multiple-inheritance is possible, with superclass order determined via L. It uses no non-core modules for any recent Perl. On Perls older than v5.10 it requires L. On Perls older than v5.14, it requires L. =head1 USAGE =head2 Defining attributes Define attributes as a list of import arguments: package Foo::Bar; use Class::Tiny qw( name id height weight ); For each attribute, a read-write accessor is created unless a subroutine of that name already exists: $obj->name; # getter $obj->name( "John Doe" ); # setter Attribute names must be valid subroutine identifiers or an exception will be thrown. You can specify lazy defaults by defining attributes with a hash reference. Keys define attribute names and values are constants or code references that will be evaluated when the attribute is first accessed if no value has been set. The object is passed as an argument to a code reference. package Foo::WithDefaults; use Class::Tiny qw/name id/, { title => 'Peon', skills => sub { [] }, hire_date => sub { $_[0]->_build_hire_date }, }; When subclassing, if multiple accessors of the same name exist in different classes, any default (or lack of default) is determined by standard method resolution order. To make your own custom accessors, just pre-declare the method name before loading Class::Tiny: package Foo::Bar; use subs 'id'; use Class::Tiny qw( name id ); sub id { ... } Even if you pre-declare a method name, you must include it in the attribute list for Class::Tiny to register it as a valid attribute. If you set a default for a custom accessor, your accessor will need to retrieve the default and do something with it: package Foo::Bar; use subs 'id'; use Class::Tiny qw( name ), { id => sub { int(rand(2*31)) } }; sub id { my $self = shift; if (@_) { return $self->{id} = shift; } elsif ( exists $self->{id} ) { return $self->{id}; } else { my $defaults = Class::Tiny->get_all_attribute_defaults_for( ref $self ); return $self->{id} = $defaults->{id}->(); } } =head2 Class::Tiny::Object is your base class If your class B already inherit from some class, then Class::Tiny::Object will be added to your C<@ISA> to provide C and C. If your class B inherit from something, then no additional inheritance is set up. If the parent subclasses Class::Tiny::Object, then all is well. If not, then you'll get accessors set up but no constructor or destructor. Don't do that unless you really have a special need for it. Define subclasses as normal. It's best to define them with L, L or L before defining attributes with Class::Tiny so the C<@ISA> array is already populated at compile-time: package Foo::Bar::More; use parent 'Foo::Bar'; use Class::Tiny qw( shoe_size ); =head2 Object construction If your class inherits from Class::Tiny::Object (as it should if you followed the advice above), it provides the C constructor for you. Objects can be created with attributes given as a hash reference or as a list of key/value pairs: $obj = Foo::Bar->new( name => "David" ); $obj = Foo::Bar->new( { name => "David" } ); If a reference is passed as a single argument, it must be able to be dereferenced as a hash or an exception is thrown. Unknown attributes in the constructor arguments will be ignored. Prior to version 1.000, unknown attributes were an error, but this made it harder for people to cleanly subclass Class::Tiny classes so this feature was removed. You can define a C method to change how arguments to new are handled. It will receive the constructor arguments as they were provided and must return a hash reference of key/value pairs (or else throw an exception). sub BUILDARGS { my $class = shift; my $name = shift || "John Doe"; return { name => $name }; }; Foo::Bar->new( "David" ); Foo::Bar->new(); # "John Doe" Unknown attributes returned from C will be ignored. =head2 BUILD If your class or any superclass defines a C method, it will be called by the constructor from the furthest parent class down to the child class after the object has been created. It is passed the constructor arguments as a hash reference. The return value is ignored. Use C for validation, checking required attributes or setting default values that depend on other attributes. sub BUILD { my ($self, $args) = @_; for my $req ( qw/name age/ ) { croak "$req attribute required" unless defined $self->$req; } croak "Age must be non-negative" if $self->age < 0; $self->msg( "Hello " . $self->name ); } The argument reference is a copy, so deleting elements won't affect data in the original (but changes will be passed to other BUILD methods in C<@ISA>). =head2 DEMOLISH Class::Tiny provides a C method. If your class or any superclass defines a C method, they will be called from the child class to the furthest parent class during object destruction. It is provided a single boolean argument indicating whether Perl is in global destruction. Return values are ignored. Errors are caught and rethrown. sub DEMOLISH { my ($self, $global_destruct) = @_; $self->cleanup(); } =head2 Introspection and internals You can retrieve an unsorted list of valid attributes known to Class::Tiny for a class and its superclasses with the C class method. my @attrs = Class::Tiny->get_all_attributes_for("Employee"); # returns qw/name ssn timestamp/ Likewise, a hash reference of all valid attributes and default values (or code references) may be retrieved with the C class method. Any attributes without a default will be C. my $def = Class::Tiny->get_all_attribute_defaults_for("Employee"); # returns { # name => undef, # ssn => undef # timestamp => $coderef # } The C method uses two class methods, C and C to set up the C<@ISA> array and attributes. Anyone attempting to extend Class::Tiny itself should use these instead of mocking up a call to C. When the first object is created, linearized C<@ISA>, the valid attribute list and various subroutine references are cached for speed. Ensure that all inheritance and methods are in place before creating objects. (You don't want to be changing that once you create objects anyway, right?) =for Pod::Coverage new get_all_attributes_for get_all_attribute_defaults_for prepare_class create_attributes =head1 RATIONALE =head2 Why this instead of Object::Tiny or Class::Accessor or something else? I wanted something so simple that it could potentially be used by core Perl modules I help maintain (or hope to write), most of which either use L or roll-their-own OO framework each time. L and L were close to what I wanted, but lacking some features I deemed necessary, and their maintainers have an even more strict philosophy against feature creep than I have. I also considered L, which has been around a long time and is heavily used, but it, too, lacked features I wanted and did things in ways I considered poor design. I looked for something else on CPAN, but after checking a dozen class creators I realized I could implement exactly what I wanted faster than I could search CPAN for something merely sufficient. In general, compared to most things on CPAN (other than Object::Tiny), Class::Tiny is smaller in implementation and simpler in API. Specifically, here is how Class::Tiny ("C::T") compares to Object::Tiny ("O::T") and Class::Accessor ("C::A"): FEATURE C::T O::T C::A -------------------------------------------------------------- attributes defined via import yes yes no read/write accessors yes no yes lazy attribute defaults yes no no provides new yes yes yes provides DESTROY yes no no new takes either hashref or list yes no (list) no (hash) Moo(se)-like BUILD/DEMOLISH yes no no Moo(se)-like BUILDARGS yes no no no extraneous methods via @ISA yes yes no =head2 Why this instead of Moose or Moo? L and L are both excellent OO frameworks. Moose offers a powerful meta-object protocol (MOP), but is slow to start up and has about 30 non-core dependencies including XS modules. Moo is faster to start up and has about 10 pure Perl dependencies but provides no true MOP, relying instead on its ability to transparently upgrade Moo to Moose when Moose's full feature set is required. By contrast, Class::Tiny has no MOP and has B non-core dependencies for Perls in the L. It has far less code, less complexity and no learning curve. If you don't need or can't afford what Moo or Moose offer, this is intended to be a reasonable fallback. That said, Class::Tiny offers Moose-like conventions for things like C and C for some minimal interoperability and an easier upgrade path. =head1 AUTHOR David Golden =head1 CONTRIBUTORS =for stopwords Dagfinn Ilmari Mannsåker David Golden Gelu Lupas Karen Etheridge Matt S Trout Olivier Mengué Toby Inkster =over 4 =item * Dagfinn Ilmari Mannsåker =item * David Golden =item * Gelu Lupas =item * Karen Etheridge =item * Matt S Trout =item * Olivier Mengué =item * Toby Inkster =back =head1 COPYRIGHT AND LICENSE This software is Copyright (c) 2013 by David Golden. This is free software, licensed under: The Apache License, Version 2.0, January 2004 =cut Inspector.pm000044400000044300152346200270007050 0ustar00package Class::Inspector; use 5.006; # We don't want to use strict refs anywhere in this module, since we do a # lot of things in here that aren't strict refs friendly. use strict qw{vars subs}; use warnings; use File::Spec (); # ABSTRACT: Get information about a class and its structure our $VERSION = '1.36'; # VERSION # If Unicode is available, enable it so that the # pattern matches below match unicode method names. # We can safely ignore any failure here. BEGIN { local $@; eval { require utf8; utf8->import; }; } # Predefine some regexs our $RE_IDENTIFIER = qr/\A[^\W\d]\w*\z/s; our $RE_CLASS = qr/\A[^\W\d]\w*(?:(?:\'|::)\w+)*\z/s; # Are we on something Unix-like? our $UNIX = !! ( $File::Spec::ISA[0] eq 'File::Spec::Unix' ); ##################################################################### # Basic Methods sub _resolved_inc_handler { my $class = shift; my $filename = $class->_inc_filename(shift) or return undef; foreach my $inc ( @INC ) { my $ref = ref $inc; if($ref eq 'CODE') { my @ret = $inc->($inc, $filename); if(@ret == 1 && ! defined $ret[0]) { # do nothing. } elsif(@ret) { return 1; } } elsif($ref eq 'ARRAY' && ref($inc->[0]) eq 'CODE') { my @ret = $inc->[0]->($inc, $filename); if(@ret) { return 1; } } elsif($ref && eval { $inc->can('INC') }) { my @ret = $inc->INC($filename); if(@ret) { return 1; } } } ''; } sub installed { my $class = shift; !! ($class->loaded_filename($_[0]) or $class->resolved_filename($_[0]) or $class->_resolved_inc_handler($_[0])); } sub loaded { my $class = shift; my $name = $class->_class(shift) or return undef; $class->_loaded($name); } sub _loaded { my $class = shift; my $name = shift; # Handle by far the two most common cases # This is very fast and handles 99% of cases. return 1 if defined ${"${name}::VERSION"}; return 1 if @{"${name}::ISA"}; # Are there any symbol table entries other than other namespaces foreach ( keys %{"${name}::"} ) { next if substr($_, -2, 2) eq '::'; return 1 if defined &{"${name}::$_"}; } # No functions, and it doesn't have a version, and isn't anything. # As an absolute last resort, check for an entry in %INC my $filename = $class->_inc_filename($name); return 1 if defined $INC{$filename}; ''; } sub filename { my $class = shift; my $name = $class->_class(shift) or return undef; File::Spec->catfile( split /(?:\'|::)/, $name ) . '.pm'; } sub resolved_filename { my $class = shift; my $filename = $class->_inc_filename(shift) or return undef; my @try_first = @_; # Look through the @INC path to find the file foreach ( @try_first, @INC ) { my $full = "$_/$filename"; next unless -e $full; return $UNIX ? $full : $class->_inc_to_local($full); } # File not found ''; } sub loaded_filename { my $class = shift; my $filename = $class->_inc_filename(shift); $UNIX ? $INC{$filename} : $class->_inc_to_local($INC{$filename}); } ##################################################################### # Sub Related Methods sub functions { my $class = shift; my $name = $class->_class(shift) or return undef; return undef unless $class->loaded( $name ); # Get all the CODE symbol table entries my @functions = sort grep { /$RE_IDENTIFIER/o } grep { defined &{"${name}::$_"} } keys %{"${name}::"}; \@functions; } sub function_refs { my $class = shift; my $name = $class->_class(shift) or return undef; return undef unless $class->loaded( $name ); # Get all the CODE symbol table entries, but return # the actual CODE refs this time. my @functions = map { \&{"${name}::$_"} } sort grep { /$RE_IDENTIFIER/o } grep { defined &{"${name}::$_"} } keys %{"${name}::"}; \@functions; } sub function_exists { my $class = shift; my $name = $class->_class( shift ) or return undef; my $function = shift or return undef; # Only works if the class is loaded return undef unless $class->loaded( $name ); # Does the GLOB exist and its CODE part exist defined &{"${name}::$function"}; } sub methods { my $class = shift; my $name = $class->_class( shift ) or return undef; my @arguments = map { lc $_ } @_; # Process the arguments to determine the options my %options = (); foreach ( @arguments ) { if ( $_ eq 'public' ) { # Only get public methods return undef if $options{private}; $options{public} = 1; } elsif ( $_ eq 'private' ) { # Only get private methods return undef if $options{public}; $options{private} = 1; } elsif ( $_ eq 'full' ) { # Return the full method name return undef if $options{expanded}; $options{full} = 1; } elsif ( $_ eq 'expanded' ) { # Returns class, method and function ref return undef if $options{full}; $options{expanded} = 1; } else { # Unknown or unsupported options return undef; } } # Only works if the class is loaded return undef unless $class->loaded( $name ); # Get the super path ( not including UNIVERSAL ) # Rather than using Class::ISA, we'll use an inlined version # that implements the same basic algorithm. my @path = (); my @queue = ( $name ); my %seen = ( $name => 1 ); while ( my $cl = shift @queue ) { push @path, $cl; unshift @queue, grep { ! $seen{$_}++ } map { s/^::/main::/; s/\'/::/g; $_ } ## no critic map { "$_" } ( @{"${cl}::ISA"} ); } # Find and merge the function names across the entire super path. # Sort alphabetically and return. my %methods = (); foreach my $namespace ( @path ) { my @functions = grep { ! $methods{$_} } grep { /$RE_IDENTIFIER/o } grep { defined &{"${namespace}::$_"} } keys %{"${namespace}::"}; foreach ( @functions ) { $methods{$_} = $namespace; } } # Filter to public or private methods if needed my @methodlist = sort keys %methods; @methodlist = grep { ! /^\_/ } @methodlist if $options{public}; @methodlist = grep { /^\_/ } @methodlist if $options{private}; # Return in the correct format @methodlist = map { "$methods{$_}::$_" } @methodlist if $options{full}; @methodlist = map { [ "$methods{$_}::$_", $methods{$_}, $_, \&{"$methods{$_}::$_"} ] } @methodlist if $options{expanded}; \@methodlist; } ##################################################################### # Search Methods sub subclasses { my $class = shift; my $name = $class->_class( shift ) or return undef; # Prepare the search queue my @found = (); my @queue = grep { $_ ne 'main' } $class->_subnames(''); while ( @queue ) { my $c = shift(@queue); # c for class if ( $class->_loaded($c) ) { # At least one person has managed to misengineer # a situation in which ->isa could die, even if the # class is real. Trap these cases and just skip # over that (bizarre) class. That would at limit # problems with finding subclasses to only the # modules that have broken ->isa implementation. local $@; eval { if ( $c->isa($name) ) { # Add to the found list, but don't add the class itself push @found, $c unless $c eq $name; } }; } # Add any child namespaces to the head of the queue. # This keeps the queue length shorted, and allows us # not to have to do another sort at the end. unshift @queue, map { "${c}::$_" } $class->_subnames($c); } @found ? \@found : ''; } sub _subnames { my ($class, $name) = @_; return sort grep { ## no critic substr($_, -2, 2, '') eq '::' and /$RE_IDENTIFIER/o } keys %{"${name}::"}; } ##################################################################### # Children Related Methods # These can go undocumented for now, until I decide if its best to # just search the children in namespace only, or if I should do it via # the file system. # Find all the loaded classes below us sub children { my $class = shift; my $name = $class->_class(shift) or return (); # Find all the Foo:: elements in our symbol table no strict 'refs'; map { "${name}::$_" } sort grep { s/::$// } keys %{"${name}::"}; ## no critic } # As above, but recursively sub recursive_children { my $class = shift; my $name = $class->_class(shift) or return (); my @children = ( $name ); # Do the search using a nicer, more memory efficient # variant of actual recursion. my $i = 0; no strict 'refs'; while ( my $namespace = $children[$i++] ) { push @children, map { "${namespace}::$_" } grep { ! /^::/ } # Ignore things like ::ISA::CACHE:: grep { s/::$// } ## no critic keys %{"${namespace}::"}; } sort @children; } ##################################################################### # Private Methods # Checks and expands ( if needed ) a class name sub _class { my $class = shift; my $name = shift or return ''; # Handle main shorthand return 'main' if $name eq '::'; $name =~ s/\A::/main::/; # Check the class name is valid $name =~ /$RE_CLASS/o ? $name : ''; } # Create a INC-specific filename, which always uses '/' # regardless of platform. sub _inc_filename { my $class = shift; my $name = $class->_class(shift) or return undef; join( '/', split /(?:\'|::)/, $name ) . '.pm'; } # Convert INC-specific file name to local file name sub _inc_to_local { # Shortcut in the Unix case return $_[1] if $UNIX; # On other places, we have to deal with an unusual path that might look # like C:/foo/bar.pm which doesn't fit ANY normal pattern. # Putting it through splitpath/dir and back again seems to normalise # it to a reasonable amount. my $class = shift; my $inc_name = shift or return undef; my ($vol, $dir, $file) = File::Spec->splitpath( $inc_name ); $dir = File::Spec->catdir( File::Spec->splitdir( $dir || "" ) ); File::Spec->catpath( $vol, $dir, $file || "" ); } 1; __END__ =pod =encoding UTF-8 =head1 NAME Class::Inspector - Get information about a class and its structure =head1 VERSION version 1.36 =head1 SYNOPSIS use Class::Inspector; # Is a class installed and/or loaded Class::Inspector->installed( 'Foo::Class' ); Class::Inspector->loaded( 'Foo::Class' ); # Filename related information Class::Inspector->filename( 'Foo::Class' ); Class::Inspector->resolved_filename( 'Foo::Class' ); # Get subroutine related information Class::Inspector->functions( 'Foo::Class' ); Class::Inspector->function_refs( 'Foo::Class' ); Class::Inspector->function_exists( 'Foo::Class', 'bar' ); Class::Inspector->methods( 'Foo::Class', 'full', 'public' ); # Find all loaded subclasses or something Class::Inspector->subclasses( 'Foo::Class' ); =head1 DESCRIPTION Class::Inspector allows you to get information about a loaded class. Most or all of this information can be found in other ways, but they aren't always very friendly, and usually involve a relatively high level of Perl wizardry, or strange and unusual looking code. Class::Inspector attempts to provide an easier, more friendly interface to this information. =head1 METHODS =head2 installed my $bool = Class::Inspector->installed($class); The C static method tries to determine if a class is installed on the machine, or at least available to Perl. It does this by wrapping around C. Returns true if installed/available, false if the class is not installed, or C if the class name is invalid. =head2 loaded my $bool = Class::Inspector->loaded($class); The C static method tries to determine if a class is loaded by looking for symbol table entries. This method it uses to determine this will work even if the class does not have its own file, but is contained inside a single file with multiple classes in it. Even in the case of some sort of run-time loading class being used, these typically leave some trace in the symbol table, so an L or L-based class should correctly appear loaded. Returns true if the class is loaded, false if not, or C if the class name is invalid. =head2 filename my $filename = Class::Inspector->filename($class); For a given class, returns the base filename for the class. This will NOT be a fully resolved filename, just the part of the filename BELOW the C<@INC> entry. print Class->filename( 'Foo::Bar' ); > Foo/Bar.pm This filename will be returned with the right separator for the local platform, and should work on all platforms. Returns the filename on success or C if the class name is invalid. =head2 resolved_filename my $filename = Class::Inspector->resolved_filename($class); my $filename = Class::Inspector->resolved_filename($class, @try_first); For a given class, the C static method returns the fully resolved filename for a class. That is, the file that the class would be loaded from. This is not necessarily the file that the class WAS loaded from, as the value returned is determined each time it runs, and the C<@INC> include path may change. To get the actual file for a loaded class, see the C method. Returns the filename for the class, or C if the class name is invalid. =head2 loaded_filename my $filename = Class::Inspector->loaded_filename($class); For a given loaded class, the C static method determines (via the C<%INC> hash) the name of the file that it was originally loaded from. Returns a resolved file path, or false if the class did not have it's own file. =head2 functions my $arrayref = Class::Inspector->functions($class); For a loaded class, the C static method returns a list of the names of all the functions in the classes immediate namespace. Note that this is not the METHODS of the class, just the functions. Returns a reference to an array of the function names on success, or C if the class name is invalid or the class is not loaded. =head2 function_refs my $arrayref = Class::Inspector->function_refs($class); For a loaded class, the C static method returns references to all the functions in the classes immediate namespace. Note that this is not the METHODS of the class, just the functions. Returns a reference to an array of C refs of the functions on success, or C if the class is not loaded. =head2 function_exists my $bool = Class::Inspector->function_exists($class, $functon); Given a class and function name the C static method will check to see if the function exists in the class. Note that this is as a function, not as a method. To see if a method exists for a class, use the C method for any class or object. Returns true if the function exists, false if not, or C if the class or function name are invalid, or the class is not loaded. =head2 methods my $arrayref = Class::Inspector->methods($class, @options); For a given class name, the C static method will returns ALL the methods available to that class. This includes all methods available from every class up the class' C<@ISA> tree. Returns a reference to an array of the names of all the available methods on success, or C if the class name is invalid or the class is not loaded. A number of options are available to the C method that will alter the results returned. These should be listed after the class name, in any order. # Only get public methods my $method = Class::Inspector->methods( 'My::Class', 'public' ); =over 4 =item public The C option will return only 'public' methods, as defined by the Perl convention of prepending an underscore to any 'private' methods. The C option will effectively remove any methods that start with an underscore. =item private The C options will return only 'private' methods, as defined by the Perl convention of prepending an underscore to an private methods. The C option will effectively remove an method that do not start with an underscore. B and C options are mutually exclusive> =item full C normally returns just the method name. Supplying the C option will cause the methods to be returned as the full names. That is, instead of returning C<[ 'method1', 'method2', 'method3' ]>, you would instead get C<[ 'Class::method1', 'AnotherClass::method2', 'Class::method3' ]>. =item expanded The C option will cause a lot more information about method to be returned. Instead of just the method name, you will instead get an array reference containing the method name as a single combined name, a la C, the separate class and method, and a CODE ref to the actual function ( if available ). Please note that the function reference is not guaranteed to be available. C is intended at some later time, to work with modules that have some kind of common run-time loader in place ( e.g C or C for example. The response from C would look something like the following. [ [ 'Class::method1', 'Class', 'method1', \&Class::method1 ], [ 'Another::method2', 'Another', 'method2', \&Another::method2 ], [ 'Foo::bar', 'Foo', 'bar', \&Foo::bar ], ] =back =head2 subclasses my $arrayref = Class::Inspector->subclasses($class); The C static method will search then entire namespace (and thus B currently loaded classes) to find all classes that are subclasses of the class provided as a the parameter. The actual test will be done by calling C on the class as a static method. (i.e. Cisa($class)>. Returns a reference to a list of the loaded classes that match the class provided, or false is none match, or C if the class name provided is invalid. =head1 SEE ALSO L, L, L =head1 AUTHOR Original author: Adam Kennedy Eadamk@cpan.orgE Current maintainer: Graham Ollis Eplicease@cpan.orgE Contributors: Tom Wyant Steffen Müller Kivanc Yazan (KYZN) =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2002-2019 by Adam Kennedy. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut Inspector/Functions.pm000044400000004731152346200270011024 0ustar00package Class::Inspector::Functions; use 5.006; use strict; use warnings; use Exporter (); use Class::Inspector (); use base qw( Exporter ); # ABSTRACT: Get information about a class and its structure our $VERSION = '1.36'; # VERSION BEGIN { our @EXPORT = qw( installed loaded filename functions methods subclasses ); our @EXPORT_OK = qw( resolved_filename loaded_filename function_refs function_exists ); #children #recursive_children our %EXPORT_TAGS = ( ALL => [ @EXPORT_OK, @EXPORT ] ); foreach my $meth (@EXPORT, @EXPORT_OK) { my $sub = Class::Inspector->can($meth); no strict 'refs'; *{$meth} = sub {&$sub('Class::Inspector', @_)}; } } 1; __END__ =pod =encoding UTF-8 =head1 NAME Class::Inspector::Functions - Get information about a class and its structure =head1 VERSION version 1.36 =head1 SYNOPSIS use Class::Inspector::Functions; # Class::Inspector provides a non-polluting, # method based interface! # Is a class installed and/or loaded installed( 'Foo::Class' ); loaded( 'Foo::Class' ); # Filename related information filename( 'Foo::Class' ); resolved_filename( 'Foo::Class' ); # Get subroutine related information functions( 'Foo::Class' ); function_refs( 'Foo::Class' ); function_exists( 'Foo::Class', 'bar' ); methods( 'Foo::Class', 'full', 'public' ); # Find all loaded subclasses or something subclasses( 'Foo::Class' ); =head1 DESCRIPTION Class::Inspector::Functions is a function based interface of L. For a thorough documentation of the available functions, please check the manual for the main module. =head2 Exports The following functions are exported by default. installed loaded filename functions methods subclasses The following functions are exported only by request. resolved_filename loaded_filename function_refs function_exists All the functions may be imported using the C<:ALL> tag. =head1 SEE ALSO L, L, L =head1 AUTHOR Original author: Adam Kennedy Eadamk@cpan.orgE Current maintainer: Graham Ollis Eplicease@cpan.orgE Contributors: Tom Wyant Steffen Müller Kivanc Yazan (KYZN) =head1 COPYRIGHT AND LICENSE This software is copyright (c) 2002-2019 by Adam Kennedy. This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. =cut Method/Modifiers/.packlist000064400000000150152346361120011517 0ustar00/usr/local/share/man/man3/Class::Method::Modifiers.3pm /usr/local/share/perl5/Class/Method/Modifiers.pm Inspector/.packlist000064400000000307152346361120010330 0ustar00/usr/local/share/man/man3/Class::Inspector.3pm /usr/local/share/man/man3/Class::Inspector::Functions.3pm /usr/local/share/perl5/Class/Inspector.pm /usr/local/share/perl5/Class/Inspector/Functions.pm Tiny/.packlist000064400000000117152346361120007304 0ustar00/usr/local/share/man/man3/Class::Tiny.3pm /usr/local/share/perl5/Class/Tiny.pm allocate-i.ri000064400000001422152352002130007102 0ustar00U:RDoc::AnyMethod[iI" allocate:ETI"Class#allocate;TF: privateo:RDoc::Markup::Document: @parts[o:RDoc::Markup::Paragraph; [I"KAllocates space for a new object of class's class and does not ;TI"Icall initialize on the new instance. The returned object must be an ;TI"instance of class.;To:RDoc::Markup::BlankLineo:RDoc::Markup::Verbatim; [I"klass = Class.new do ;TI" def initialize(*args) ;TI" @initialized = true ;TI" end ;TI" ;TI" def initialized? ;TI" @initialized || false ;TI" end ;TI" end ;TI" ;TI"*klass.allocate.initialized? #=> false;T: @format0: @fileI" object.c;T:0@omit_headings_from_table_of_contents_below0I"!class.allocate() -> obj ;T0[I"();T@FI" Class;TcRDoc::NormalClass00new-i.ri000064400000001055152352002130006111 0ustar00U:RDoc::AnyMethod[iI"new:ETI"Class#new;TF: privateo:RDoc::Markup::Document: @parts[o:RDoc::Markup::Paragraph; [ I"ECalls #allocate to create a new object of class's class, ;TI"?then invokes that object's #initialize method, passing it ;TI"Bargs. This is the method that ends up getting called ;TI"?whenever an object is constructed using .new.;T: @fileI" object.c;T:0@omit_headings_from_table_of_contents_below0I"%class.new(args, ...) -> obj ;T0[I" (*args);T@FI" Class;TcRDoc::NormalClass00new-c.ri000064400000002247152352002130006107 0ustar00U:RDoc::AnyMethod[iI"new:ETI"Class::new;TT: privateo:RDoc::Markup::Document: @parts[ o:RDoc::Markup::Paragraph; [I"GCreates a new anonymous (unnamed) class with the given superclass ;TI":(or Object if no parameter is given). You can give a ;TI">class a name by assigning the class object to a constant.;To:RDoc::Markup::BlankLineo; ; [I"GIf a block is given, it is passed the class object, and the block ;TI"4is evaluated in the context of this class like ;TI"#class_eval.;T@o:RDoc::Markup::Verbatim; [I"fred = Class.new do ;TI" def meth1 ;TI" "hello" ;TI" end ;TI" def meth2 ;TI" "bye" ;TI" end ;TI" end ;TI" ;TI">a = fred.new #=> #<#:0x100376b98> ;TI""a.meth1 #=> "hello" ;TI" a.meth2 #=> "bye" ;T: @format0o; ; [I"EAssign the class to a constant (name starting uppercase) if you ;TI"+want to treat it like a regular class.;T: @fileI" object.c;T:0@omit_headings_from_table_of_contents_below0I"sClass.new(super_class=Object) -> a_class Class.new(super_class=Object) { |mod| ... } -> a_class ;T0[I" (*args);T@(FI" Class;TcRDoc::NormalClass00subclasses-i.ri000064400000001345152352002130007471 0ustar00U:RDoc::AnyMethod[iI"subclasses:ETI"Class#subclasses;TF: privateo:RDoc::Markup::Document: @parts[o:RDoc::Markup::Paragraph; [I";Returns an array of classes where the receiver is the ;FI"Bdirect superclass of the class, excluding singleton classes. ;FI"4The order of the returned array is not defined.;Fo:RDoc::Markup::BlankLineo:RDoc::Markup::Verbatim; [ I"class A; end ;TI"class B < A; end ;TI"class C < B; end ;TI"class D < A; end ;TI" ;TI"$A.subclasses #=> [D, B] ;TI"!B.subclasses #=> [C] ;TI"C.subclasses #=> [];T: @format0: @fileI" object.c;T:0@omit_headings_from_table_of_contents_below0I"subclasses -> array ;F0[I"();T@FI" Class;TcRDoc::NormalClass00cdesc-Class.ri000064400000005707152352002130007226 0ustar00U:RDoc::NormalClass[iI" Class:ET@I" Module;To:RDoc::Markup::Document: @parts[o;;[: @fileI" class.c;T:0@omit_headings_from_table_of_contents_below0o;;[o:RDoc::Markup::Paragraph;[I";Extends any Class to include _json_creatable?_ method.;T; I" ext/json/lib/json/common.rb;T; 0o;;[o; ;[I"FClasses in Ruby are first-class objects---each is an instance of ;TI"class Class.;To:RDoc::Markup::BlankLineo; ;[I"0Typically, you create a new class by using:;T@o:RDoc::Markup::Verbatim;[I"class Name ;TI"0 # some code describing the class behavior ;TI" end ;T: @format0o; ;[I"MWhen a new class is created, an object of type Class is initialized and ;TI"7assigned to a global constant (Name in this case).;T@o; ;[I"FWhen Name.new is called to create a new object, the ;TI"-#new method in Class is run by default. ;TI":This can be demonstrated by overriding #new in Class:;T@o; ;[I"class Class ;TI" alias old_new new ;TI" def new(*args) ;TI"2 print "Creating a new ", self.name, "\n" ;TI" old_new(*args) ;TI" end ;TI" end ;TI" ;TI"class Name ;TI" end ;TI" ;TI"n = Name.new ;T;0o; ;[I"produces:;T@o; ;[I"Creating a new Name ;T;0o; ;[ I"DClasses, modules, and objects are interrelated. In the diagram ;TI"Fthat follows, the vertical arrows represent inheritance, and the ;TI"(BasicObject)-------|-... ;TI"8 ^ | ^ | ;TI"8 | | | | ;TI"< Object---------|----->(Object)---------|-... ;TI"8 ^ | ^ | ;TI"8 | | | | ;TI"8 +-------+ | +--------+ | ;TI"8 | | | | | | ;TI"< | Module-|---------|--->(Module)-|-... ;TI"8 | ^ | | ^ | ;TI"8 | | | | | | ;TI"< | Class-|---------|---->(Class)-|-... ;TI"8 | ^ | | ^ | ;TI"8 | +---+ | +----+ ;TI"* | | ;TI";obj--->OtherClass---------->(OtherClass)-----------...;T;0; I" object.c;T; 0; 0; 0[[[[[I" class;T[[: public[[:protected[[: private[[I"new;TI" object.c;T[I" instance;T[[;[[;[[;[ [I" allocate;T@j[I"inherited;T@j[I"json_creatable?;TI" ext/json/lib/json/common.rb;T[I"new;T@j[I"subclasses;T@j[I"superclass;T@j[[U:RDoc::Context::Section[i0o;;[; 0; 0[I" class.c;TI" ext/json/lib/json/common.rb;TI" object.c;T@ZcRDoc::TopLevelsuperclass-i.ri000064400000001425152352002130007505 0ustar00U:RDoc::AnyMethod[iI"superclass:ETI"Class#superclass;TF: privateo:RDoc::Markup::Document: @parts[ o:RDoc::Markup::Paragraph; [I"AReturns the superclass of class, or nil.;To:RDoc::Markup::BlankLineo:RDoc::Markup::Verbatim; [ I"%File.superclass #=> IO ;TI")IO.superclass #=> Object ;TI".Object.superclass #=> BasicObject ;TI"class Foo; end ;TI"class Bar < Foo; end ;TI"&Bar.superclass #=> Foo ;T: @format0o; ; [I"CReturns nil when the given class does not have a parent class:;T@o; ; [I"%BasicObject.superclass #=> nil;T; 0: @fileI" object.c;T:0@omit_headings_from_table_of_contents_below0I".class.superclass -> a_super_class or nil ;T0[I"();T@FI" Class;TcRDoc::NormalClass00inherited-i.ri000064400000001363152352002130007275 0ustar00U:RDoc::AnyMethod[iI"inherited:ETI"Class#inherited;TF: privateo:RDoc::Markup::Document: @parts[ o:RDoc::Markup::Paragraph; [I"JCallback invoked whenever a subclass of the current class is created.;To:RDoc::Markup::BlankLineo; ; [I" Example:;T@o:RDoc::Markup::Verbatim; [I"class Foo ;TI"$ def self.inherited(subclass) ;TI"* puts "New subclass: #{subclass}" ;TI" end ;TI" end ;TI" ;TI"class Bar < Foo ;TI" end ;TI" ;TI"class Baz < Bar ;TI" end ;T: @format0o; ; [I"produces:;T@o; ; [I"New subclass: Bar ;TI"New subclass: Baz;T; 0: @fileI" object.c;T:0@omit_headings_from_table_of_contents_below0I"inherited(subclass) ;T0[I" (p1);T@&FI" Class;TcRDoc::NormalClass00json_creatable%3f-i.ri000064400000001042152352002130010565 0ustar00U:RDoc::AnyMethod[iI"json_creatable?:ETI"Class#json_creatable?;TF: privateo:RDoc::Markup::Document: @parts[o:RDoc::Markup::Paragraph; [ I"BReturns true if this class can be used to create an instance ;TI"Gfrom a serialised JSON string. The class has to implement a class ;TI"Kmethod _json_create_ that expects a hash as first parameter. The hash ;TI"&should include the required data.;T: @fileI" ext/json/lib/json/common.rb;T:0@omit_headings_from_table_of_contents_below000[I"();T@FI" Class;TcRDoc::NormalClass00