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

Define 'new' method on model classes #174

Closed
connorshea opened this issue Sep 15, 2019 · 6 comments · Fixed by #179
Closed

Define 'new' method on model classes #174

connorshea opened this issue Sep 15, 2019 · 6 comments · Fixed by #179
Labels
bug Something isn't working

Comments

@connorshea
Copy link
Contributor

connorshea commented Sep 15, 2019

Describe the bug:
ActiveRecord overrides the new method for all Model classes, e.g. User.new.

It's defined like this in activerecord.rbi:

module ActiveRecord::Inheritance::ClassMethods
  def new(attributes = nil, &block); end
end

And then User, or any other model, inherits that method.

Expected behavior:

I could have an app/controllers/users_controller.rb file like this:

class UsersController < ApplicationController
  def create
    @user = User.new({ username: 'connor' }) # @user is T.untyped because `new` is overridden.
    respond_to do |format|
      if @user.save
        format.html { redirect_to @user, success: "#{@user.username} was successfully created." }
    end
  end
end

The method should be generated as part of Sorbet Rails so its return type can be dynamically set:

class User
  sig { params(args: T.untyped, block: T.untyped).returns(User) }
  def self.new(*args, &block); end
end

Unfortunately it can't just be self_type because that doesn't return an instance of the caller :/

@connorshea connorshea added the bug Something isn't working label Sep 15, 2019
@connorshea
Copy link
Contributor Author

Actually, since we know what parameters it takes can we use the correct method signature?

class User
  sig { params(attributes: T.untyped, block: T.untyped).returns(User) }
  def self.new(attributes = nil, &block); end
end

@connorshea
Copy link
Contributor Author

@manhhung741 IIRC, you mentioned at once point that the Sorbet team didn't want to add a special type that'd return an instance of a class (e.g. instead of T.self_type it'd be T.instance_of_self_type), did they say why?

@hdoan741
Copy link
Contributor

hdoan741 commented Sep 15, 2019 via email

@connorshea
Copy link
Contributor Author

create is handled in sorbet-typed right now, but it just returns T.untyped.

@hdoan741
Copy link
Contributor

hdoan741 commented Sep 15, 2019 via email

@connorshea
Copy link
Contributor Author

Where should I put the create_method for this? 🤔

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