Skip to content

Commit

Permalink
- Added the METHODS method for user-defined objects which returns a…
Browse files Browse the repository at this point in the history
…n Hash of String=>LazyMethod pairs.
  • Loading branch information
trizen committed Jul 7, 2015
1 parent aaa3382 commit 6122dd9
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
15 changes: 15 additions & 0 deletions lib/Sidef/Variable/Class.pm
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,21 @@ package Sidef::Variable::Class {
$self->{class};
}

sub METHODS {
my ($self) = @_;

state $x = require Scalar::Util;

my %alias;
my %methods;
while (my ($key, $value) = each %{$self->{method}}) {
$methods{$key} =
($alias{Scalar::Util::refaddr($value)} //= Sidef::Variable::LazyMethod->new(obj => $self, method => $value));
}

Sidef::Types::Hash::Hash->new(%methods);
}

sub def_method {
my ($self, $name, $block) = @_;
$self->{method}{$name} = $block;
Expand Down
8 changes: 8 additions & 0 deletions lib/Sidef/Variable/Class.pod
Original file line number Diff line number Diff line change
Expand Up @@ -49,3 +49,11 @@ Return the
Aliases: I<is_an>

=cut

=head2 METHODS

Class.METHODS() -> I<Obj>

Return the

=cut
13 changes: 12 additions & 1 deletion lib/Sidef/Variable/LazyMethod.pm
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,18 @@ package Sidef::Variable::LazyMethod {
my ($self, @args) = @_;

my ($method) = ($AUTOLOAD =~ /^.*[^:]::(.*)$/);
my $call = ref($self->{method}) eq 'CODE' ? $self->{method} : $self->{method}->get_value;
my $call = $self->{method};

if (ref($call) eq 'Sidef::Types::Block::Code') {
if ($method eq 'call') {
return $call->call($self->{obj}, @{$self->{args}}, @args);
}
return $call->call($self->{obj}, @{$self->{args}})->$method(@args);
}

if (ref($call) ne 'CODE') {
$call = $call->get_value;
}

if ($method eq 'call') {
return $self->{obj}->$call(@{$self->{args}}, @args);
Expand Down

0 comments on commit 6122dd9

Please sign in to comment.