Prefer & over try for chaining methods
Description of the proposal
If we want to safely chain methods onto objects that could potentially be nil
we currently have &
(ruby) and try
(ActiveSupport).
The subtle difference between these is that try
would swallow the exception if the object was not nil, but did not respond to the method:
[79] pry(main)> Project.find_by_id(-1).try(:hello)
Project Load (49.3ms) SELECT "projects".* FROM "projects" WHERE "projects"."id" = $1 LIMIT $2 [["id", -1], ["LIMIT", 1]]
↳ (pry):93
=> nil
[80] pry(main)> Project.find_by_id(-1)&.hello
Project Load (4.7ms) SELECT "projects".* FROM "projects" WHERE "projects"."id" = $1 LIMIT $2 [["id", -1], ["LIMIT", 1]]
↳ (pry):94
=> nil
[81] pry(main)> Project.first.try(:hello)
Project Load (16.2ms) SELECT "projects".* FROM "projects" ORDER BY "projects"."id" ASC LIMIT $1 [["LIMIT", 1]]
↳ (pry):95
=> nil
[82] pry(main)> Project.first&.hello
Project Load (14.3ms) SELECT "projects".* FROM "projects" ORDER BY "projects"."id" ASC LIMIT $1 [["LIMIT", 1]]
↳ (pry):96
NoMethodError: undefined method `hello' for #<Project id:2 gitlab-org/gitlab-shell>
from /Users/bvl/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/activemodel-5.1.7/lib/active_model/attribute_methods.rb:432:in `method_missing'
I personally prefer using &
for that reason. Should we add a cop to suggest & autocorrect that?
-
Mention the proposal in the next backend weekly call and the #backend channel to encourage contribution -
Proceed with the proposal once 50% of the maintainers have weighed in, and 80% of the votes are 👍 -
Once approved, mention it again in the next backend weekly call and the #backend channel