The Perl and Raku Conference 2025: Greenville, South Carolina - June 27-29 Learn more

NAME

Rubyish::Attribute - ruby-like accessor builder: attr_accessor, attr_writer and attr_reader.

VERSION

This document is for version 1.2

SYNOPSIS

#!/usr/bin/env perl
use 5.010;
use strict;
{
package Animal;
# import attr_accessor, attr_writer and attr_reader
BEGIN {
attr_accessor "name", "color", "type";
}
# pass a list as the only one parameter
# invoke it in compile time to avoid using parenthesis when using instance variable as below
# then create a constructer based on hashref
sub new {
$class = shift;
bless {}, $class;
}
sub rename_as {
my ($self, $new_name) = @_;
__name__ = $new_name;
# __name__ is accurately a lvalue subroutine &__name__() which refer to $self->{name}
# now it looks like a instance variable.
}
1;
}
$dogy = Animal->new()->name("rock")
->color("black")->type("unknown");
# new Animal with three attribute
say $dogy->name; #=> rock
say $dogy->color; #=> black
say $dogy->type; #=> unknown

FUNCTIONS

attr_accessor(@list)

attr_accessor provides getters double as setters. Because all setter return instance itself, now we can manipulate object in ruby way more than ruby.

attr_accessor qw(name color type master)
$dogy = Animal->new()->name("lucky")->color("white")
->type("unknown")->master("shelling");

Each attribute could be read by getter as showing in synopsis.

attr_reader(@list)

attr_reader create only getter for the class you call it

attr_reader qw(name) # pass a list
$dogy = Animal->new({name => "rock"}) # if we write initialize function in constructor
$dogy->name() #=> rock
$dogy->name("jack") #=> undef (with warn msg)

attr_writer(@list)

attr_writer create only setter for the class you call it.

attr_writer qw(name) # pass a list
$dogy = Animal->new()->name("lucky") # initialize and set and get instance itself
$dogy->name("jack") #=> instance itself
$dogy->name #=> undef (with warn msg)

DEPENDENCE

Want

SEE ALSO

autobox::Core, List::Rubyish, Class::Accessor::Lvalue, Want

http://ruby-doc.org/core-1.8.7/classes/Module.html#M000423

http://chupei.pm.org/2008/11/rubyish-attribute.html chinese introduction

AUTHOR

shelling <navyblueshellingford at gmail.com>

gugod <gugod at gugod.org>

acknowledgement

Thanks to gugod providing testing script and leading me on the way of perl

REPOSITORY

host: http://github.com/shelling/rubyish-attribute/tree/master

checkout: git clone git://github.com/shelling/rubyish-attribute.git

BUGS

please report bugs to <shelling at cpan.org> or <gugod at gugod.org>

COPYRIGHT & LICENCE

Copyright (C) 2008 shelling, gugod, all rights reserved.

Release under MIT (X11) Lincence.