Question

I'm using DBIx::Class::Schema::Loader to generate (and constantly regenerate) result classes from a db schema.

Is there an idomatic way to add methods to the generated classes?

What I currently do is to define the additional methods near the code that's using the result classes:

package Some::Package::Using::Result::Classes;
use My::Schema::Result::Hello;

...
1;

package My::Schema::Result::Hello;

sub str {
  my $self = shift;
  sprintf("Hello: %s, %d", $self->name, $self->age);
}
1;

(As you can see, what I'm trying to do is add a toString()-like function.)

Was it helpful?

Solution

If you look near the top of your generated result classes, you'll see this comment.

# Created by DBIx::Class::Schema::Loader
# DO NOT MODIFY THE FIRST PART OF THIS FILE

Notice, it says that you shouldn't modify the "first part" of the file.

At the bottom of the file, you'll see this.

# Created by DBIx::Class::Schema::Loader v0.07039 @ 2014-01-30 20:13:57
# DO NOT MODIFY THIS OR ANYTHING ABOVE! md5sum:3eYA3YhJdL90HQRfNN07EA

# You can replace this text with custom code or comments, and it will be preserved on regeneration

So you can add whatever code you want to the result class file as long as you put it under the line containing the MD5 hash. Anything you put there will still be there when you regenerate the class.

OTHER TIPS

I do not know if this is idiomatic, but it is more compact:

*My::Schema::Result::Hello::str = sub
    my $self = shift;
    sprintf("Hello: %s, %d", $self->name, $self->age);
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top