| 1 | |||
| 2 | package Class::XSAccessor; | ||
| 3 | |||
| 4 | sub import { | ||
| 5 | my $class = shift; | ||
| 6 | my %args; | ||
| 7 | if ( ref($_[0]) eq "HASH" ) { | ||
| 8 | %args = %{$_[0]}; | ||
| 9 | } | ||
| 10 | else { | ||
| 11 | %args = @_; | ||
| 12 | } | ||
| 13 | |||
| 14 | my $caller = caller(0); | ||
| 15 | |||
| 16 | for my $param ( "getters", "setters", "accessors" ) { | ||
| 17 | if (ref($args{$param}) eq 'ARRAY') { | ||
| 18 | $args{$param} = { map { $_ => $_ } @{$args{$param}} }; | ||
| 19 | } | ||
| 20 | } | ||
| 21 | |||
| 22 | my $getters = delete $args{getters}; | ||
| 23 | if ($getters) { | ||
| 24 | for my $name (keys %$getters) { | ||
| 25 | my $key = $getters->{$name}; | ||
| 26 | *{"${caller}::${name}"} = sub { | ||
| 27 | $_[0]->{$key} | ||
| 28 | }; | ||
| 29 | } | ||
| 30 | } | ||
| 31 | |||
| 32 | my $setters = delete $args{setters}; | ||
| 33 | if ($setters) { | ||
| 34 | for my $name (keys %$setters) { | ||
| 35 | my $key = $setters->{$name}; | ||
| 36 | *{"${caller}::${name}"} = sub { | ||
| 37 | $_[0]->{$key} = $_[1] | ||
| 38 | }; | ||
| 39 | } | ||
| 40 | } | ||
| 41 | |||
| 42 | my $accessors = delete $args{accessors}; | ||
| 43 | if ($accessors) { | ||
| 44 | for my $name (keys %$accessors) { | ||
| 45 | my $key = $accessors->{$name}; | ||
| 46 | # print STDERR "generate accessor for $caller $class $name => $key\n"; | ||
| 47 | # | ||
| 48 | # TODO - add message: | ||
| 49 | # "Class::XSAccessor: invalid instance method invocant: no hash ref supplied" | ||
| 50 | # | ||
| 51 | *{"${caller}::${name}"} = sub { | ||
| 52 | @_ > 1 | ||
| 53 | ? $_[0]->{$key} = $_[1] | ||
| 54 | : $_[0]->{$key} | ||
| 55 | }; | ||
| 56 | } | ||
| 57 | } | ||
| 58 | |||
| 59 | if (keys %args) { | ||
| 60 | die "not implemented: Class::XSAccessor @{[ keys %args ]}"; | ||
| 61 | } | ||
| 62 | } | ||
| 63 | |||
| 64 | 1; | ||
| 65 | |||
| 66 | __END__ |