Skip to content

Using and creating typed objects

Aaron Christiansen edited this page Sep 13, 2020 · 2 revisions

Overview

Typed objects are the key part of any Parlour code; a definition is added to the final type file for each typed object you've created.

Currently there are two available object types: RbiObject and RbsObject, for RBI and RBS files respectively.

All typed objects need to be a child of a namespace: a class or a module. (The root namespace, passed as an argument to Plugin#generate or returned by Generator#root, is a special namespace which is neither a class nor a module.)

The methods listed below are the methods which you should use to create new typed objects, or add information to existing ones.

All of the create methods all optionally take a block which the new typed object instance is yielded to. This means that there are two styles for creating nested typed object structures, and you can use whichever you prefer:

root.create_module('Foo') do |foo|
  foo.create_method('bar')
end

# or, equivalently...

foo = root.create_module('Foo')
foo.create_method('bar')

The first and only positional argument is the name of the object, while all other arguments are keyword arguments.

Note: before 0.6.0, the name of the object was also a keyword argument, name:.

Note: most add methods were removed in 0.5.0 and replaced with corresponding create methods.

Available Methods

These are the create methods for each namespace. Click on any of these to see their documentation.

RBI

RBS

Using comments

In both RBI and RBS, the following methods are available for using comments:

It is important to understand that add_comment adds a comment directly to that object, meaning that it will appear above the definition in the type file, no matter where add_comment was called.

root.create_module('Foo') do |foo|
  foo.add_comment('This is a comment.')
  foo.create_method(name: 'bar')
end

The above code produces the following RBI. Note the position of the comment:

# typed: strong
# This is a comment.
module Foo
  def bar; end
end

If the intention was to add the comment to the method bar instead, then you can either use add_comment_to_next_child, or call add_comment on the method instead.

root.create_module('Foo') do |foo|
  foo.add_comment_to_next_child('This is a comment on bar.')
  foo.create_method('bar') do |bar|
    foo.add_comment('This is another comment on bar.')
  end
end

This produces:

# typed: strong
module Foo
  # This is a comment on bar.
  # This is another comment on bar.
  def bar; end
end
Clone this wiki locally