1use warnings; 2use strict; 3 4use Test::More; 5 6use lib qw(t/lib); 7use DBICTest; 8 9package My::Schema::Result::User; 10 11use strict; 12use warnings; 13use base qw/DBIx::Class::Core/; 14 15### Define what our admin class is, for ensure_class_loaded() 16my $admin_class = __PACKAGE__ . '::Admin'; 17 18__PACKAGE__->table('users'); 19 20__PACKAGE__->add_columns( 21 user_id => { retrieve_on_insert => 1 }, 22 qw( email password firstname lastname active admin ), 23); 24 25__PACKAGE__->set_primary_key('user_id'); 26 27sub inflate_result { 28 my $self = shift; 29 my $ret = $self->next::method(@_); 30 if ( $ret->admin ) { ### If this is an admin, rebless for extra functions 31 $self->ensure_class_loaded($admin_class); 32 bless $ret, $admin_class; 33 } 34 return $ret; 35} 36 37sub hello { 38 return "I am a regular user."; 39} 40 41package My::Schema::Result::User::Admin; 42 43use strict; 44use warnings; 45use base qw/My::Schema::Result::User/; 46 47# This line is important 48__PACKAGE__->table('users'); 49 50sub hello { 51 return "I am an admin."; 52} 53 54sub do_admin_stuff { 55 return "I am doing admin stuff"; 56} 57 58package My::Schema; 59 60use base qw/DBIx::Class::Schema/; 61 62My::Schema->register_class( Admin => 'My::Schema::Result::User::Admin' ); 63My::Schema->register_class( User => 'My::Schema::Result::User' ); 64 651; 66 67package main; 68my $user_data = { 69 email => 'someguy@place.com', 70 password => 'pass1', 71 admin => 0 72}; 73 74my $admin_data = { 75 email => 'someadmin@adminplace.com', 76 password => 'pass2', 77 admin => 1 78}; 79 80ok( my $schema = My::Schema->connect(DBICTest->_database) ); 81 82ok( 83 $schema->storage->dbh->do( 84"create table users (user_id, email, password, firstname, lastname, active, admin)" 85 ) 86); 87 88{ 89 my $user = $schema->resultset('User')->create($user_data); 90 my $admin = $schema->resultset('User')->create($admin_data); 91 92 is( ref $user, 'My::Schema::Result::User' ); 93 94 local $TODO = 'New objects should also be inflated'; 95 is( ref $admin, 'My::Schema::Result::User::Admin' ); 96} 97 98my $user = $schema->resultset('User')->single($user_data); 99my $admin = $schema->resultset('User')->single($admin_data); 100 101is( ref $user, 'My::Schema::Result::User' ); 102is( ref $admin, 'My::Schema::Result::User::Admin' ); 103 104is( $user->password, 'pass1' ); 105is( $admin->password, 'pass2' ); 106is( $user->hello, 'I am a regular user.' ); 107is( $admin->hello, 'I am an admin.' ); 108 109ok( !$user->can('do_admin_stuff') ); 110ok( $admin->can('do_admin_stuff') ); 111 112done_testing; 113