[Dbix-class] DBIx::Class::Helper::ResultSet::Random for Resultsets only known at runtime

"José Diaz Seng" josediazseng at gmx.de
Tue Nov 6 12:42:23 GMT 2012


I would like to use DBIx::Class::Helper::ResultSet::Random for Resultsets where
the source names are only known at runtime, but I can't get this to work. I only 
started to learn about DBIC, so please don't be too shocked by the code I have 
written up so far :) I tried to follow the Synopsis on CPAN for 
DBIx::Class::Helper::ResultSet::Random module, i.e.


 # note that this is normally a component for a ResultSet
 package MySchema::ResultSet::Bar;

 use strict;
 use warnings;

 use parent 'DBIx::Class::ResultSet';


 # in code using resultset:
 my $random_row = $schema->resultset('Bar')->rand->single;

--------end quote-----

My DBIC schema is created at runtime using make_schema_at and I tried to 
retrieve a random record for the source with name T. So the first thing to 
do was making the rand method available in package DBIC::Schema::ResultSet::T. 
Note that I do not know the source until runtime, therefore the code is 
contained in a string to be eval-ed as follows (I added some print statements
to check things work as expected):

-----start code----
eval <<'END';
package DBIC::Schema::ResultSet::T; 
use parent "DBIx::Class::ResultSet";

print "now in package ".__PACKAGE__."\n";

my $methods = Class::Inspector->methods("DBIC::Schema::ResultSet::T");
foreach (@{$methods}) {
  print "found method rand!\n" if /\brand\b/;
-----end code----

This part seems to work fine.

But later on I tried to use the rand function (note that I used an eval
here too since I hoped the late evaluation would perhaps help):

-----start code----
my $random_row;
eval '$random_row = $dbic_schema->resultset("T")->rand->single;';
$error = $@;
croak $error if $@;
-----end code----

The error message I got was 
"Can't locate object method "rand" via package "DBIx::Class::ResultSet" at..."

Do you know how can I turn $dbic_schema->resultset("T") into an object of type 
DBIC::Schema::ResultSet::T or if there is a better approach?

Thanks & best regards

More information about the DBIx-Class mailing list