Skip to content

Instantly share code, notes, and snippets.

@marcoarthur
Created July 8, 2024 18:38
Show Gist options
  • Save marcoarthur/92a1eb19fec0279d2b91a25392998910 to your computer and use it in GitHub Desktop.
Save marcoarthur/92a1eb19fec0279d2b91a25392998910 to your computer and use it in GitHub Desktop.
a fake book creation for test with dbix
use warnings;
use strict;
package MyApp::Schema {
use strict;
use warnings;
use base 'DBIx::Class::Schema';
#__PACKAGE__->load_namespaces;
1;
}
package MyApp::Schema::Result::Book {
use strict;
use warnings;
use base 'DBIx::Class::Core';
__PACKAGE__->load_components('InflateColumn::DateTime', 'Core');
__PACKAGE__->table('books');
__PACKAGE__->add_columns(
'id' => {
data_type => 'integer',
is_auto_increment => 1,
},
'title' => {
data_type => 'text',
},
'author' => {
data_type => 'text',
},
);
__PACKAGE__->set_primary_key('id');
__PACKAGE__->has_many(
'pages' => 'MyApp::Schema::Result::Page',
{ 'foreign.book_id' => 'self.id' }
);
1;
}
package MyApp::Schema::Result::Page {
use strict;
use warnings;
use base 'DBIx::Class::Core';
__PACKAGE__->load_components('InflateColumn::DateTime', 'Core');
__PACKAGE__->table('pages');
__PACKAGE__->add_columns(
'id' => {
data_type => 'integer',
is_auto_increment => 1,
},
'book_id' => {
data_type => 'integer',
},
'page_number' => {
data_type => 'integer',
},
'text' => {
data_type => 'text',
},
'image' => {
data_type => 'blob',
is_nullable => 1,
},
'word_count' => {
data_type => 'integer',
is_nullable => 1,
},
);
__PACKAGE__->set_primary_key('id');
__PACKAGE__->belongs_to(
'book' => 'MyApp::Schema::Result::Book',
{ 'foreign.id' => 'self.book_id' }
);
1;
}
package FakeBooks {
use Data::Fake qw/Core Names Text Dates/;
use Mojo::Collection qw(c);
use feature qw(signatures);
sub new {
my $book = fake_hash(
{
author => fake_name(),
title => fake_sentences(1),
pages => fake_array(fake_int(10,60), fake_paragraphs(fake_int(1,10))),
}
);
my $fake = sub {
my $b = $book->();
$b->{pages} = c($b->{pages}->@*)
->map(
sub ($text) { return +{ text => $text } }
)->each(
sub ($page, $idx) {
$page->{page_number} = $idx;
$page->{word_count} = scalar(split/\s+/, $page->{text});
}
)->to_array;
$b;
};
return bless { faker => $fake }, 'FakeBooks';
}
sub next ($self){
$self->{faker}->();
}
}
package main;
use DDP;
#use Test2::V0;
sub setup_schema {
my $sch = MyApp::Schema->connect('dbi:SQLite:dbname=:memory:');
my @results = qw/MyApp::Schema::Result::Page MyApp::Schema::Result::Book/;
for my $class (@results) {
my ($name) = $class =~ /::(\w+)$/;
$sch->register_class($name, $class);
}
return $sch;
}
my $sch = setup_schema;
my $book_gen = FakeBooks->new;
my $data = $book_gen->next;
my $book = $sch->resultset('Book')->new( $data );
p $book;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment