rbs icon indicating copy to clipboard operation
rbs copied to clipboard

Specify the type of evaluation context of a block

Open TSMMark opened this issue 4 years ago • 2 comments

In this example, the binding / evaluation context of the block is said to be self

https://github.com/ruby/rbs/blob/287808c00f7809e0c1261074c6eb90990d8d1d21/core/basic_object.rbs#L172-L185

  # Executes the given block within the context of the receiver (*obj*). In order
  # to set the context, the variable `self` is set to *obj* while the code is
  # executing, giving the code access to *obj*'s instance variables.  Arguments
  # are passed as block parameters.
  #
  #     class KlassWithSecret
  #       def initialize
  #         @secret = 99
  #       end
  #     end
  #     k = KlassWithSecret.new
  #     k.instance_exec(5) {|x| @secret+x }   #=> 104
  #
  def instance_exec: [U, V] (*V args) { (*V args) -> U } -> U

However, I believe self is the default context of a block — But if I want to specify a context other than self for a block, how can that be accomplished?

I've searched through many specs, examples, and source code in this repo and can't find out how to do it.


Example:

Using Sequel gem, Sequel::Model has a class method: dataset_module, which receives a block. Methods defined in this block will have the evaluation context of an instance of a Sequel::Dataset.

I've tried many different variations of a syntax like this with no success:

def self.dataset_module: () { (self: Sequel::Dataset ) -> void } -> void

Is this currently unsupported by RBS or am I just missing it in the documentation?

Any advice, direction, or link to source code exemplifying this would be very much appreciated — thank you in advance

TSMMark avatar Mar 17 '21 18:03 TSMMark

I would like to see this implemented too as it would be a big help for some of the blocks in Rails which do not use self as the context of a block.

hjwylde avatar May 04 '21 13:05 hjwylde

Indeed. This is a very common pattern in Ruby, which is why I still kind of feel like it maybe is already supported by RBS, but I am simply unable to figure out how.

Any advice from maintainers would be awesome. Looking forward to it

TSMMark avatar May 04 '21 15:05 TSMMark