ruby-on-rails - 在 Ruby 中循环遍历多个数组

标签 ruby-on-rails ruby refactoring

我有多个 ActiveRecord 子类 Item 的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:

Item A maintenance required in 5 days
Item B payment required in 6 days
Item A payment required in 7 days
Item B maintenance required in 8 days

我目前有两个查询,用于查找maintenancepayment 项目(非排他性查询),并输出如下内容:

<%- item_p = nil -%>
<%- item_m = nil -%>

<%- loop do -%>
  <% item_p ||= @items_p.shift %>
  <% item_m ||= @items_m.shift %>

  <%- if item_p.nil? and item_m.nil? then break -%>
  <%- elsif item_p and (item_m.nil? or item_p.paymt < item_m.maint) then -%>
    <%= item_p.name %> payment required in ...
  <%- elsif item_m and (item_p.nil? or item_m.maint < item_p.paymt) then -%>
    <%= item_m.name %> maintenance required in ...
  <%- end -%>
<%- end -%>

有什么方法可以改善上述(丑陋的)代码的可读性?

最佳答案

拥抱鸭子类型并确保您的对象是多态。您希望您的付款项目与维护项目可比较,以便对它们进行分类。

所以,假设你有一个 Payment和一个 Maintenance类:

module Due
  include Comparable

  # Compare this object with another. Used for sorting.
  def <=>(other)
    self.due <=> other.due
  end
end

class Payment < ActiveRecord::Base
  include Due

  alias_method :due, :payment

  def action
    "#{name} requires payment"
  end
end

class Maintenance < ActiveRecord::Base
  include Due

  alias_method :due, :maintenance

  def action
    "#{name} requires maintenance"
  end
end

看看我们如何创建 action , due<=> 两个类中的方法?我们还注意包含 Ruby 内置模块 Comparable .这使我们能够执行以下操作:

# Assuming 'payment' and 'maintenance' are date fields...
a = Payment.new :payment => 3.days.from_now
b = Maintenance.new :maintenance => 2.days.from_now
[a, b].sort
#=> [b, a]

然后 View 变得很简单:

<% (@payment_items + @maintenance_items).sort.each do |item| %>
  <%= item.action %> in <%= distance_of_time_in_words_to_now(item.due) %><br/>
<% end %>

我确定我没有正确了解您的实现细节,但我希望这能让您了解如何解决您的问题。

关于ruby-on-rails - 在 Ruby 中循环遍历多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6271238/

相关文章:

ruby-on-rails - rspec 中的多线程 ActiveRecord 请求

java - 如何在java中重构、修复和优化这个字符替换功能

Javascript:重构现有代码以分离关注点,我们如何使用类/原型(prototype)并从它自己的对象的方法中调用?

ruby-on-rails - Rails 3.2,处理损坏的请求体(MultiJson::DecodeError)

ruby - 像 Rails 这样的多 gem Ruby 项目如何管理每个 gem 的并行开发?

ruby-on-rails - 为什么 Rails Weekday 索引与 Ruby 的不同?

ruby-on-rails - macOS, rails : "Failed to build gem native extension"

java - 通过重构简化代码

javascript - Rails 4 JavaScript/JQuery 通过编辑 Controller 操作渲染多个部分

javascript - 将 HTML 数据属性设置为整数数组