rails-style-guide
rails-style-guide copied to clipboard
Cop idea: merge `.first` || `.create!` into `.first_or_create!`
# bad
def method
users.where(name: name).first ||
users.where(name: name).create!
end
# bad
def method
users.where(name: name).first ||
users.create!(name: name)
end
# good
def method
users.where(name: name).first_or_create!
end
And for similar methods like find_or_create_by, find_or_create_by!, find_or_initialize_by, first_or_create, first_or_create!, first_or_initialize, create_or_find_by and create_or_find_by!
This is a matter of style. Before deciding, let's discuss it in the style guide.
The "good" style is preferable to me, because it helps me organize my code better.
Compare with this example (from my project):
def hsh
{ name: name }
end
# before
def method1
users.where(hsh).first || users.create!(hsh)
end
def method2
users.where(hsh).first || users.where(hsh.merge(premium: true)).create!
end
# after
def method1
users.where(hsh).first_or_create!
end
def method2
users.where(hsh).first || users.where(hsh.merge(premium: true)).create!
end
Isn't first_or_create
deprecated? https://github.com/rails/rails/pull/29584#issuecomment-311427304
@Linuus Good catch. I'll close this proposal.
Maybe we should add a cop that warns when first_or_create
is used instead 😬
Let’s leave it out to the Rails team to print deprecation warnings.