簡體   English   中英

rails查詢對象中的“調用的分配分支條件大小太高”

[英]"Assignment Branch Condition size for call is too high" in rails query object

我在 rails 項目中有一個查詢對象,它使用多個過濾器(費用、名稱、專業、多年的經驗)搜索資源。

class SearchDoctors
  attr_accessor :initial_scope, :search_params

  def self.call(initial_scope, search_params)
    new(initial_scope, search_params).call
  end

  def initialize(initial_scope, search_params)
    @initial_scope = initial_scope
    @search_params = search_params
  end


  # Assignment branch condition on call method
  def call
    scoped = filter_by_speciality(initial_scope, search_params[:speciality])
    scoped = filter_by_name(scoped, search_params[:name])
    scoped = filter_by_fees(scoped,
                            search_params[:fees_from],
                            search_params[:fees_to])
    filter_by_years_of_experience(scoped,
                                  search_params[:experience_from],
                                  search_params[:experience_to])
  end
end

過濾器方法是為簡潔起見刪除的私有方法。

call 方法給出了“賦值分支條件太高”的 rubocop 警告,這是有道理的,因為它做了很多。 我如何重構它以繞過 rubocop 警告?

我看到了一些類似的問題,但沒有一個能解決我的問題。

在 Rails 中有很多方法可以在不使用重新分配的情況下構造作用域,這只是一種懶惰的方法。

您可以在模型本身上制作可鏈接的范圍:

class Doctor < ApplicationRecord
  def self.filter_by_speciality(speciality)
    speciality.present ? self.where(speciality: speciality) : self     
  end

  def self.filter_by_name(name)
    name.present ? self.where(name: name) : self     
  end
end

這會讓你打電話:

Doctor.filter_by_speciality(params[:speciality])
      .filter_by_name(params[:name])
      # etc

始終返回 self 或其他范圍將防止 nil 錯誤。

您還可以使用.merge來組合范圍。

Doctor.where(name: 'John').merge(
  Doctor.where(specialty: 'pediatrician')
)

因此,如果您從這些方法中重構scoped參數開始,您可以組合一個作用域數組並將它們合並在一起:

def call
  # not going to list them all. 
  scopes = [filter_by_speciality(search_params[:speciality]), filter_by_name(search_params[:name])]
  scopes.compact.each_with_object(initial_scope) do |filter, memo|
     memo.merge(filter)
   end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM