Hi, All

I've been very frustrated to write something like:

my $m = Jifty->app_class(Model => "Foo")->new
$m->load($id)

Just to load a record, so I've come up with a Jifty::ModelHelpers
module that auto-generate
a method for each model and collection in the app. So you can write
this instead:

my $m = Foo(1);

For collections too:

my $foos = FooCollection;

This is equivalent of

my $foos = Jifty->app_class(Model => "FooCollection")->new;
$foos->unlaimit;

Foo and FooCollection are auto-generated subs. The helper code is attached.

I would like you guys to tell me if something like this should be in
core. I'll make a release of such helper on my own
if not :)

-- 
Cheers,
Kang-min Liu
package Jifty::ModelHelpers;
use strict;
use Exporter;

our @ISA = qw(Exporter);
our @EXPORT;
our $VERSION = "0.01";

{
    require Jifty::Schema;
    my @models = map { s/.*::(.+)$/$1/;  $_; } Jifty::Schema->new->models;

    no strict 'refs';
    for my $model (@models) {
        if ( index($model, "Collection") >= 0) {
            *{"$model"} = sub {
                my @args = @_;
                my $obj = Jifty->app_class(Model => "$model")->new;
                if (@args == 0) {
                    $obj->unlimit;
                }
                elsif (@args % 2 == 0) {
                }
                return $obj;
            }
        }
        else {
            *{"$model"} = sub {
                my @args = @_;
                my $obj = Jifty->app_class(Model => "$model")->new;
                if (@args == 1) {
                    $obj->load($args[0]);
                }
                if (@args % 2 == 0) {
                    $obj->load_from_cols($args[0]);
                }
                return $obj;
            };
        }
        push @EXPORT, "&${model}";
    }
}

1;
_______________________________________________
jifty-devel mailing list
jifty-devel@lists.jifty.org
http://lists.jifty.org/cgi-bin/mailman/listinfo/jifty-devel

Reply via email to