Metaprogrammatically defining methods with required, optional, required keyword and optional keyword parameters?

John Carter <[email protected]> Mon, 17 Jun 2019 10:20:53 +1200
Newsgroups gmane.comp.lang.ruby.general
Message-ID <CAFD1m3Fe9fa7t4kM+S0DGAx=p+8qsX23OZQQA08uarn+LiFtOw@mail.gmail.com>
I'm want to do meta programming in the sense of writing ruby to create
a new ruby method.

Module#define_method exists....

   https://ruby-doc.com/core/Module.html#method-i-define_method

However modern ruby now has required parameters, default parameters,
required keyword parameters and optional keyword parameters and an
optional a block parameter.

So Method.parameters seems to understand all these things....

  > def foo( bar, baz, but = 0, joke:, nojoke: 10, &block);end
=> :foo
  > method(:foo).parameters
=> [[:req, :bar], [:req, :baz], [:opt, :but], [:keyreq, :joke], [:key,
:nojoke], [:block, :block]]

Module#define_method would seem to be what I want.... but... that
defers the problem of specifying the parameters to Proc, Method,
UnboundMethod or block....

Proc.new basically converts a block into a Proc.

Method.new and UnboundMethod.new do not exist.

block's themselves are not quite first class objects.

I guess I could achieve the required magic by Module.class_eval(
string) ... but that seems crude...


Any idea how to define (at run time) the parameter list for a method?

I have done it, somewhat crudely by

         define_method( :my_constructed_at_run_time_method) do
|*positional,**keyword|
             # Implement all the parameter checking and raise
ArgumentError in the right places
             #  in raw ruby...
        end

..but that seems duplicating all the logic around parameter checking
that must already exist somewhere in the Ruby runtime..




--
John Carter
Phone : (64)(3) 358 6639
Tait Electronics
PO Box 1645 Christchurch
New Zealand

-- 
This Communication is Confidential. We only send and receive email on the

basis of the terms set out at www.taitradio.com/email_disclaimer 
<http://www.taitradio.com/email_disclaimer>

Unsubscribe: <mailto:[email protected]?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-talk>