pocke / rbs_rails

Apache License 2.0
285 stars 33 forks source link

Output absolute type name #262

Closed pocke closed 1 year ago

pocke commented 1 year ago

Problem

I received a bug report at an online meeting. If the user defines a class with the same name as the core class, RBS Rails outputs incorrect types.

For example:

# The user defines MyApp::Integer
module MyApp
  class Integer
  end
end

# app/models/my_app/article.rb
module MyApp
  class Article < ApplicationRecord
  end
end

In this case, RBS Rails outputs the following RBS file.

module MyApp
  class Article < ::ApplicationRecord
    extend _ActiveRecord_Relation_ClassMethods[Article, ActiveRecord_Relation, Integer]

    # (snip)
  end
end

Integer in the extend means ::Integer, but it will be resolved as ::MyApp::Integer in this environment.

Solution

Print types with absolute path. For example:

module MyApp
  class Article < ::ApplicationRecord
    extend _ActiveRecord_Relation_ClassMethods[::MyApp::Article, ::MyApp::Article::ActiveRecord_Relation, ::Integer]

    # (snip)
  end
end

It solves this problem.

By the way, we can use relative paths for ::MyApp::Aritcle and ::MyApp::Article::ActiveRecord_Relation because user-defined classes do not change the resolved class. But I think it prints all classes as an absolute path for consistency.


By the way, I do not prefer absolute class names on handwritten RBS files. The user does not need to edit the RBS file generated by RBS Rails. So it prioritizes accuracy over writability. But the user edits the hand-written RBS file. Therefore it prioritizes writability. It can use an absolute path if the relative path is ambiguous.