0

我正在构建名为 import_items 的功能。

逻辑有点复杂和顺序:

# Step 1. See if User has a remote source set up.
# Step 2. If yes (it's set up) - load that CSV file.
# Step 3. Convert CSV to Hashes 
# Step 4. Reject CSV rows that don't belong to the user 
#         (export feed can have items of other users)
# Step 5. Convert remaining hashes into hashes my DB can accept
# Step 6. For each hash in that array start Item.delay.create(hash)
#         (want it to go through Sidekiq because user can import say 500 items, 
#          which takes time, some of them can fail etc)

如果一个步骤失败 - 不应完成所有后续步骤。

所有这些都必须在后台工作中完成。

您通常如何编写这种功能?

我现在想到的唯一方法是将它分成几个步骤,并为每个步骤做一个延迟的工作:

class User < ActiveRecord::Base
  def import_items
    self.delay.load_CSV if self.dms and self.dms_id
  end

  def load_CSV
    result = ... (loading CSV file, convert rows to hashes)
    self.delay.keep_only_user_items(result) if result
  end

  def keep_only_user_items(all_items)
    result = ... (rejecting wrong items)
    self.delay.convert_to_proper_hashes(result)
  end

  ... # etc
end

这是一个好方法吗?

我只想测试每个步骤以确保它们正常工作。

4

1 回答 1

0

你不需要在这里的DelayedJob 提前返回,它只会使事情复杂化。只需将逻辑分解为小方法,出现错误时不要继续。简而言之,delay从你的代码中删除,你应该会很好。

您通常如何编写非常长且复杂的方法?

您不会编写冗长而复杂的方法。你编写小而简单的方法。它会得到回报的。

class User < ActiveRecord::Base
  def import_items
    load_CSV if self.dms and self.dms_id
  end

  def load_CSV
    result = ... (loading CSV file, convert rows to hashes)
    keep_only_user_items(result) if result
  end

  def keep_only_user_items(all_items)
    result = ... (rejecting wrong items)
    convert_to_proper_hashes(result)
  end
end
于 2013-10-22T09:31:19.977 回答