Home > database >  Get method called-as str in the callee
Get method called-as str in the callee

Time:04-04

I would like to introspect the tail end of a method call from the callee side.

Right now I am doing this explicitly...

# caller side
s.pd: '.shape';
s.pd: '.to_json("test.json")';
s.pd: '.iloc[2] = 23';

# callee side
method pd( Str $call ) {
    given $call {
        when /shape/   { ... }
        when /to_json/ { ... }
        #etc
    }
}

BUT, I would like to do this by way of a 'slang method call', something like this made up code...

# caller side
s.pd.shape;
s.pd.to_json("test.json");
s.pd.iloc[2] = 23;
^ ^^ ^^^^^^^^^^^^^^^^^^^$
|  |       |
|  |       L a q// str I can put into eg. a custom Grammar
|  |
|  L general method name
|
L invocant

#callee side
method pd( ?? ) {
    my $called-as-str = self.^was-called-as;
    say $called-as-str;   #'pd.to_json("test.json")'
    ...
}

(HOW) can this be done in raku?

Since there are 422 calls to handle, of many arity patterns, answers that require the declaration of 422 methods and signatures in the called Class will be less attractive.

CodePudding user response:

Per @jonathans comment, the raku docs state:

A method with the special name FALLBACK will be called when other means to resolve the name produce no result. The first argument holds the name and all following arguments are forwarded from the original call. Multi methods and sub-signatures are supported.

class Magic {
    method FALLBACK ($name, |c(Int, Str)) {
    put "$name called with parameters {c.raku}"  }
};
Magic.new.simsalabim(42, "answer");
 
# OUTPUT: «simsalabim called with parameters ⌈\(42, "answer")⌋␤»

So my code example would read:

# callee side
class Pd-Stub {
    method FALLBACK ($name, Str $arg-str ) {
        say "$name called with args: <<$arg-str>>"
    }
}

class Series { 
    has Pd-Stub $.pd 
}

my \s = Series.new;

# caller side
s.pd.shape;                 #shape called with args: <<>>        
s.pd.to_json("test.json");  #to_json called with args: <<test.json>>
s.pd.iloc[2] = 23;          #iloc called with args: <<>>

#iloc needs to use AT-POS and Proxy to handle subscript and assignment
  • Related