arlyxiao / best-practice

1 stars 0 forks source link

规范化构建 ruby on rails 系统 #84

Open arlyxiao opened 2 years ago

arlyxiao commented 2 years ago

本文尝试从构建一套系统会用到的库,代码或者工具入手。其中包括如何规范化代码写法,常用的类库,常见的 API 用法等。

你可能需要 RuboCop 格式化代码

添加 gem 到 Gemfile

gem 'rubocop', require: false

命令行执行

bundle exec rubocop
bundle exec rubocop -a

具体参考 https://www.honeybadger.io/blog/linting-formatting-ruby/


如何正确使用异常

不要直接使用 Exception 类

begin
  do_something()
rescue Exception => e
  # Don't do this. This will swallow every single exception. Nothing gets past it. 
end

应该使用 StandardError

begin
  do_something()
rescue StandardError => e
  # Only your app's exceptions are swallowed. Things like SyntaxErrror are left alone. 
end

具体参考 https://www.honeybadger.io/blog/ruby-exception-vs-standarderror-whats-the-difference/


使用 concerns 模块化处理不同逻辑,让 controller 变得更干净

在 concerns 目录下创建 trashable.rb

module Trashable
  extend ActiveSupport::Concern

  included do
    scope :existing, -> { where(trashed: false) }
    scope :trashed, -> { where(trashed: true) }
  end

  def trash
    update_attribute :trashed, true
  end
end

然后 controller 引用

include Trashable

具体参考 https://blog.appsignal.com/2020/09/16/rails-concers-to-concern-or-not-to-concern.html