Connor Shea
Connor Shea

Reputation: 870

How to write a type signature for a block with Sorbet?

I'm currently trying to add types to some core Rails methods, and one of them is respond_to. It can be used with a block, like so:

respond_to do |format|
  format.html
  format.json { render json: @companies }
end

The problem I'm having is how to type this exactly, since the docs on T.proc are pretty minimal. The format parameter is an instance of ActionController::MimeResponds::Collector. There's no need for the block to return anything (e.g. it's not like Array#select where it evaluates the block and the block returns a boolean).

I think this is the way you'd want to write the signature?:

sig do
  params(
    mimes: T.nilable(Symbol),
    block: T.proc.params(arg0: ActionController::MimeResponds::Collector).void
  ).void
end
def respond_to(*mimes, &block); end

(We can ignore the *mimes argument for now, that's not important)

It seems like this works, but I just want to make sure I'm understanding the way T.proc is supposed to be used.

(Note there's an issue with blocks that are nilable causing a regression to T.untyped, but that's not what I'm confused on at the moment)

Upvotes: 1

Views: 1157

Answers (1)

user537862
user537862

Reputation: 481

Seems like correct usage of signatures to me.

BTW, Additions to docs are super welcome!

Upvotes: 1

Related Questions