新人求思路。现在在做一个项目,做到关于数据还原这一块,写了一个方法,如下
def restore_record record_id, activities
activity_ids = activities.map(&:id)
if self.name == "Prize"
record = self.deleted.find(record_id)
if activity_ids.include?(record.activity_id)
record.restore
return true
else
return false
end
elsif self.name == "Apply"
record = self.deleted.friendly.find(record_id)
if activity_ids.include?(record.activity_id)
self.restore(record.id, :recursive => true)
return true
else
return false
end
elsif self.name == "Activity"
record = self.deleted.friendly.find(record_id)
if activities.include?(record)
self.restore(record.id, :recursive => true)
return true
else
return false
end
else
return false
end
end
虽然上面的方法能正常使用,但是看上去太臃肿,重复的代码太多了,所以进行一次简单的重构,如下
def restore_record record_id, activities
if ["Prize", "Apply", "Activity"].include?(self.name)
self.send "restore_#{self.name.downcase}", record_id, activities
else
return false
end
end
def restore_prize record_id, activities
activity_ids = activities.map(&:id)
record = self.deleted.find(record_id)
if activity_ids.include?(record.activity_id)
record.restore
return true
else
return false
end
end
def restore_apply record_id, activities
activity_ids = activities.map(&:id)
record = self.deleted.friendly.find(record_id)
if activity_ids.include?(record.activity_id)
self.restore(record.id, :recursive => true)
return true
else
return false
end
end
def restore_activity record_id, activities
record = self.deleted.friendly.find(record_id)
if activities.include?(record)
self.restore(record.id, :recursive => true)
return true
else
return false
end
end
但是重构后发现自己根本没有能力消除更多的重复的代码,但是想了很久依然没能想到能继续消除重复代码的办法,不知道有没有大神能给予一些建议或者思路,小弟在这里非常感谢!