我正在构建名为 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
这是一个好方法吗?
我只想测试每个步骤以确保它们正常工作。