I seem to be having difficulty understanding how to correctly work with classes in Raku.
I am trying to create a 'Database' class that I will use throughout my cro application. However I don't seem to understand how to deal with setting instance variables at object construction (BUILD?) time.
The class below shows an example of the problem I am having when calling it with:
Calling:
my $db = Database.new(dsn => 'update me!');
say "what value is foo: " ~ $db.what-is-foo(); # prints "what value is foo: 0" but expecting 123
My Class:
use DB::Pg;
class Database {
has Str $.dsn is required;
has DB::Pg $!dbh = Nil;
has Int $!foo = 0;
method new (:$dsn) {
my $dbh = DB::Pg.new(conninfo => :$dsn);
my $foo = 123;
return self.bless(:$dsn, dbh => $dbh, foo => $foo);
}
method what-is-foo() {
return $!foo;
}
}
So in my class constructor I would like to pass in a named arg for the database dsn. In the new method I plan to connect, and set an instance variable to the connection handle.
In this example I am using a simple integer (foo) as a test.
So far I have found the docs here to not include an example of this type of pattern, except pehaps:
use DB::Pg;
class Database {
has Str $.dsn is required;
has DB::Pg $!dbh = Nil;
has Int $!foo = 0;
submethod BUILD(:$dsn) {
$!dbh = DB::Pg.new(conninfo => :$dsn);
$!foo = 123;
}
method what-is-foo() {
return $!foo;
}
}
But that gives me:
The attribute '$!dsn' is required, but you did not provide a value for it.
Any help would be greatly appreciated!