我正在构建名为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
这是一个好方法吗?
我只是想测试每一步以确保它们正常工作。
答案 0 :(得分:0)
这里不需要DelayedJob提前返回,只会使事情复杂化。只需将逻辑分解为小方法,并在出现错误时不要继续。简而言之,从您的代码中删除delay
,您应该做得很好。
你怎么写真的很长&amp;复杂的方法?
您不会编写冗长而复杂的方法。你写的是小而简单的方法。它会得到回报。
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