25 September 2011
it's a story following the previous one. and this one will be shorter.

I got Net-GitHub 0.40_02 released few minutes ago. with
* Gists, Git Data, Orgs supports
* methods on fly

there are still something to do like Pagination and MIME-Types. but most of the functions should be working now.

big thanks to Moose team, I becomes a little smarter than yesterday.

yesterday I was dumb. I wrote every methods with sub, with arguments fix, with ->query or check DELETE status. lots of duplication codes.

I cleaned all the code up with __PACKAGE__->meta->add_method. now all the code looks very clean and easy to maintain.



the main tricky here is the ->meta->add_method.

## build methods on fly
sub __build_methods {
    my $package = shift;
    my %methods = @_;
    
    foreach my $m (keys %methods) {
        my $v = $methods{$m};
        my $url = $v->{url};
        my $method = $v->{method} || 'GET';
        my $args = $v->{args} || 0; # args for ->query
        my $check_status = $v->{check_status};
        my $is_u_repo = $v->{is_u_repo}; # need auto shift u/repo
        
        $package->meta->add_method( $m => sub {
            my $self = shift;
            
            # count how much %s inside u
            my $n = 0; while ($url =~ /\%s/g) { $n++ }
            
            ## if is_u_repo, both ($user, $repo, @args) or (@args) should be supported
            if ( ($is_u_repo or index($url, '/repos/%s/%s') > -1) and @_ < $n + $args) {
                unshift @_, ($self->u, $self->repo);
            }

            # make url, replace %s with real args
            my @uargs = splice(@_, 0, $n);
            my $u = sprintf($url, @uargs);
            
            # args for json data POST
            my @qargs = $args ? splice(@_, 0, $args) : ();
            if ($check_status) { # need check Response Status
                my $old_raw_response = $self->raw_response;
                $self->raw_response(1); # need check header
                my $res = $self->query($method, $u, @qargs);
                $self->raw_response($old_raw_response);
                return index($res->header('Status'), $check_status) > -1 ? 1 : 0;
            } else {
                return $self->query($method, $u, @qargs);
            }
        } );
    }
}

next step will be Pagination and MIME-types. and later.

Thanks


blog comments powered by Disqus