Search code examples
rubyiderubyminecode-completion

Assert type for code completion in RubyMine


Ruby isn't a statically-typed language, so it isn't really possible for a code completion engine to know exactly what type any function will return.

However, sometimes the programmer knows. Take the code below, which uses metaprogramming to 'confuse' code completion:

class Example
  define_method :foo do
    2 + 2
  end

  def bar
    foo_result = foo
  end
end

A static analyser doesn't know that foo exists, so it can't provide code completion for it. Even though foo will always be an Integer and we know that, I only get code completion for BasicObject.

enter image description here

Is there a way to tell a code completion engine which type I know something is going to be, so that I get better completion results, which is simply ignored by the interpreter?


Solution

  • Turns out this is partially possible using "Annotations" in the form of comments, which are documented at: https://www.jetbrains.com/help/ruby/using-annotations.html

    You can add types to ambiguous methods or variables like this:

    # @return [String]
    def mystery_method
        # @type [Integer]
        foo = nil
    end
    

    It doesn't appear that you can create entirely new methods using this approach though, for example for metaprogramming-driven methods.