本文?
Ruby 静态代码分析的标准 gem战警.每条规则都称为警察。和,RuboCop 导轨是用于将 Rails 规则添加到 RuboCop 的 gem。
一次偶然的机会,我认为通过检查 RuboCop Rails 添加的 Cops(规则),这将是了解 Rails 未知功能的好机会。所以,我尝试查看2022/09/09(星期五)发布的2.16.0版本的内容
然后,不出所料,我学到了很多,因为只有我不知道的东西!所以,我想分享我在这篇文章中实际学到的东西?
示例:RuboCop Rails 2.16.0 添加了警察
#714:添加新的Rails/FreezeTimecop。
# Bad ?
travel_to(Time.now)
travel_to(DateTime.now)
travel_to(Time.current)
travel_to(Time.zone.now)
travel_to(Time.now.in_time_zone)
travel_to(Time.current.to_time)
# Good ?
freeze_time
第744章:添加新的Rails/WhereMissingcop。
- 如果您想使用 LEFT JOIN 来缩小没有相关记录的记录失踪应该使用方法。
- Rails 6.1 中添加了缺失的方法。
# Bad ?
Post.left_joins(:author).where(authors: { id: nil })
# Good ?
Post.where.missing(:author)
第587章:添加新的Rails/RootPathnameMethods cop。
- 由 Rails.root.join 返回路径名使用对象操作文件时,应使用 Pathname 对象的方法,而不是使用 File 类。
# Bad ?
File.open(Rails.root.join('db', 'schema.rb'))
File.open(Rails.root.join('db', 'schema.rb'), 'w')
File.read(Rails.root.join('db', 'schema.rb'))
File.binread(Rails.root.join('db', 'schema.rb'))
File.write(Rails.root.join('db', 'schema.rb'), content)
File.binwrite(Rails.root.join('db', 'schema.rb'), content)
# Good ?
Rails.root.join('db', 'schema.rb').open
Rails.root.join('db', 'schema.rb').open('w')
Rails.root.join('db', 'schema.rb').read
Rails.root.join('db', 'schema.rb').binread
Rails.root.join('db', 'schema.rb').write(content)
Rails.root.join('db', 'schema.rb').binwrite(content)
#752:添加Rails/TopLevelHashWithIndifferentAccess警察。
-
::HashWithIndifferentAccess已弃用,请改用ActiveSupport::HashWithIndifferentAccess。- 从 Rails 5.1 开始软弃用。
# Bad ?
HashWithIndifferentAccess.new(foo: 'bar')
# Good ?
ActiveSupport::HashWithIndifferentAccess.new(foo: 'bar')
#759:添加新的Rails/ActionControllerFlashBeforeRender 警察。
-
flash.now在render之前设置闪烁消息时应使用。- 否则,flash 消息可能会无意中持续到下一个操作。
- 参考:我尝试验证flash和flash.now的区别-Qiita
# Bad ?
class HomeController < ApplicationController
def create
flash[:alert] = "msg"
render :index
end
end
# Good ?
class HomeController < ApplicationController
def create
flash.now[:alert] = "msg"
render :index
end
end
第749章:添加新的Rails/ActiveSupportOnLoad cop。
- 如果你想对 Rails 提供的类进行猴子补丁ActiveSupport.on_load应该使用。
- 这样做会延迟加载补丁,以便仅在需要时加载它。
# Bad ?
ActiveRecord::Base.include(MyClass)
# Good ?
ActiveSupport.on_load(:active_record) { include MyClass }
第747章:添加Rails/ToSWithArgument警察。
-
因为
to_s(format)从 Rails 7.0 开始被弃用。- 由于 to_s 方法在 Ruby 3.1 中进行了优化,Rails 7.0 避免了覆盖此方法并利用了优化。
- 参考:弃用
to_s(format)支持to_formatted_s(format)by rafaelfranca Pull Request #43772 rails/rails GitHub
# Bad ?
obj.to_s(:delimited)
# Good ?
obj.to_formatted_s(:delimited)
概括
您可以通过查看特定版本的 RuboCop Rails 了解 Rails 中您不了解或已弃用的功能,以了解添加 Cop 的背景。我觉得这个调查很有用,所以我决定每次更新版本时都检查一下发布内容。大家喜欢的时候就去看看
参考
原创声明:本文系作者授权爱码网发表,未经许可,不得转载;
原文地址:https://www.likecs.com/show-308626751.html