Skip to content

Commit

Permalink
Support has_and_belongs_to_many
Browse files Browse the repository at this point in the history
  • Loading branch information
tk0miya committed Nov 10, 2024
1 parent 5f5c8f8 commit eedafdf
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 0 deletions.
19 changes: 19 additions & 0 deletions lib/rbs_rails/active_record.rb
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ class ActiveRecord_Associations_CollectionProxy < ::ActiveRecord::Associations::
private def associations
[
has_many,
has_and_belongs_to_many,
has_one,
belongs_to,
].join("\n")
Expand All @@ -140,6 +141,24 @@ def #{singular_name}_ids=: (::Array[::Integer]) -> ::Array[::Integer]
end.join("\n")
end

private def has_and_belongs_to_many
klass.reflect_on_all_associations(:has_and_belongs_to_many).map do |a|
@dependencies << a.klass.name

singular_name = a.name.to_s.singularize
type = Util.module_name(a.klass)
collection_type = "#{type}::ActiveRecord_Associations_CollectionProxy"
@dependencies << collection_type

<<~RUBY.chomp
def #{a.name}: () -> #{collection_type}
def #{a.name}=: (#{collection_type} | ::Array[#{type}]) -> (#{collection_type} | ::Array[#{type}])
def #{singular_name}_ids: () -> ::Array[::Integer]
def #{singular_name}_ids=: (::Array[::Integer]) -> ::Array[::Integer]
RUBY
end.join("\n")
end

private def has_one
klass.reflect_on_all_associations(:has_one).map do |a|
@dependencies << a.klass.name unless a.polymorphic?
Expand Down
2 changes: 2 additions & 0 deletions sig/rbs_rails/active_record.rbs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ class RbsRails::ActiveRecord::Generator

def has_many: () -> String

def has_and_belongs_to_many: () -> String

def has_one: () -> String

def belongs_to: () -> String
Expand Down
4 changes: 4 additions & 0 deletions test/expectations/user.rbs
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,10 @@ class User < ::ApplicationRecord
end
include GeneratedAttributeMethods

def blogs: () -> ::Blog::ActiveRecord_Associations_CollectionProxy
def blogs=: (::Blog::ActiveRecord_Associations_CollectionProxy | ::Array[::Blog]) -> (::Blog::ActiveRecord_Associations_CollectionProxy | ::Array[::Blog])
def blog_ids: () -> ::Array[::Integer]
def blog_ids=: (::Array[::Integer]) -> ::Array[::Integer]
def avatar_attachment: () -> ::ActiveStorage::Attachment?
def avatar_attachment=: (::ActiveStorage::Attachment?) -> ::ActiveStorage::Attachment?
def build_avatar_attachment: (?untyped) -> ::ActiveStorage::Attachment
Expand Down

0 comments on commit eedafdf

Please sign in to comment.