Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 重构小型服务_Ruby On Rails_Ruby_Ruby On Rails 4_Refactoring - Fatal编程技术网

Ruby on rails 重构小型服务

Ruby on rails 重构小型服务,ruby-on-rails,ruby,ruby-on-rails-4,refactoring,Ruby On Rails,Ruby,Ruby On Rails 4,Refactoring,我有这个小代码 class ReadReportService def self.get_oldest_reports(count, filter={}) reports = Report.unread.order('created_at DESC').limit(count) reports = reports.where(category: filter[:category]) if filter[:category].present? reports = re

我有这个小代码

class ReadReportService
  def self.get_oldest_reports(count, filter={})
    reports = Report.unread.order('created_at DESC').limit(count)

    reports = reports.where(category: filter[:category]) if filter[:category].present?
    reports = reports.where(cost: filter[:cost]) if filter[:cost].present?
    reports = reports.where(email: filter[:email]) if filter[:email].present?

    reports.update_all(status: Report.statuses[:read])

    reports.to_a
  end
end

我能做得更好更好吗?如何改进现有的检查哈希参数?

它应该在
报告中
模型中:

class Report < ActiveRecord::Base
  STATUSES = {read: 'read', pending: 'pending'}

  scope :ordered_limit, ->(limit) { order('created_at DESC').limit(limit) }
  scope :filter_category, ->(category) { where(category: category) if category }
  scope :filter_cost, ->(cost) { where(cost: cost) if cost }
  scope :filter_email, ->(email) { where(email: email) if email }

  def self.get_oldest_reports(count, filter={})
    reports = unread.ordered_limit(count)
      .filter_category(filter[:category])
      .filter_cost(cost)
      .filter_email(email)
    reports.update_all(status: STATUSES[:read])

    reports.to_a # not sure you need it
  end
end
类报告(限制){order('created_at DESC')。限制(limit)}
范围:筛选器_category,->(category){where(category:category)if category}
范围:筛选成本,->(成本){其中(成本:成本)如果成本}
范围:筛选电子邮件,->(电子邮件){where(电子邮件:电子邮件)if email}
def self.get_最早的_报告(计数,筛选器={})
报告=未读。已排序\u限制(计数)
.filter\u类别(filter[:category])
.filter_成本(cost)
.filter_电子邮件(电子邮件)
报告。全部更新(状态:状态[:读取])
reports.to#不确定您是否需要它
结束
结束

如果您想简化与过滤器一起工作的代码,可以执行以下操作:

reports = Report.unread.order('created_at DESC').limit(count)
[:category, :cost, :email].each do |key|
  reports = reports.where(key => filter[key]) if filter[key].present?
end
reports.update_all(status: Report.statuses[:read])
reports.to_a
顺便说一下,在名为
get\u xxx
的方法中调用
update\u all
不是个好主意。如果我得到了一些东西,我不希望有什么东西会改变

另外,如果你喜欢OneLiner,你甚至可以这样做:

reports.where(filter.slice(:category, :cost, :email).select { |k, v| v.present? })

我需要这个作为服务,因为我的类有更多的def;)