Skip to content
This repository has been archived by the owner on Jul 5, 2023. It is now read-only.

Generate methods for ActiveStorage attachments #148

Closed
connorshea opened this issue Aug 30, 2019 · 2 comments · Fixed by #149
Closed

Generate methods for ActiveStorage attachments #148

connorshea opened this issue Aug 30, 2019 · 2 comments · Fixed by #149
Labels
bug Something isn't working

Comments

@connorshea
Copy link
Contributor

connorshea commented Aug 30, 2019

Describe the bug:

SorbetRails doesn't currently generate methods for ActiveStorage attachments. For example, in my Rails app users have avatars and games have covers, but neither of these are typed.

Steps to reproduce:

class User < ApplicationRecord
  has_one_attached :avatar
end
class Game < ApplicationRecord
  has_one_attached :cover
end

In hidden.rbi we have some methods like this:

module User::GeneratedAssociationMethods
  def avatar(); end

  def avatar=(attachable); end
end

Expected behavior:

It should return either ActiveStorage::Attached::One or ActiveStorage::Attached::Many depending on the definition in the model.

This is what I'd expect to see in game.rbi:

module Game::GeneratedAttributeMethods
  extend T::Sig
  
  sig { returns(T.nilable(ActiveStorage::Attached::One)) }
  def cover; end

  sig { params(attachable: T.untyped).returns(T.untyped) }
  def cover=(attachable); end

  # or, if we had something defined like `has_many_attached :covers`
  sig { returns(T.nilable(ActiveStorage::Attached::Many)) }
  def covers; end

  sig { params(attachable: T.untyped).returns(T.untyped) }
  def covers=(*attachables); end
end

I'm not entirely sure what the setters take or return, unfortunately.

Versions:

  • Ruby: 2.6.2
  • Rails: 6.0.0
  • Sorbet:
  • Sorbet-Rails: 0.5.3 (master)
@connorshea connorshea added the bug Something isn't working label Aug 30, 2019
@connorshea
Copy link
Contributor Author

connorshea commented Aug 30, 2019

I think you can get attachment names for a model like this

User.attachment_reflections.keys
# => ["avatar"]

You can also get the type of attachment (has_one_attached vs has_many_attached) like this:

User.attachment_reflections.values.map { |x| x.class }
# }=> [ActiveStorage::Reflection::HasOneAttachedReflection]

Or, to simplify things:

User.attachment_reflections.transform_values { |x| x.class }
=> {"avatar"=>ActiveStorage::Reflection::HasOneAttachedReflection}

@hdoan741
Copy link
Contributor

hdoan741 commented Aug 30, 2019 via email

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug Something isn't working
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants