我有一个类来比较导入的数据和数据库值。我结束了这么多条件,以至于rubocop大声喊叫。所以我将方法分解为更小的方法,但这些方法中仍有条件。这是代码:
之前
class Utility
attr_reader :im_data, :db_data
def initialize(im_data, db_data)
@im_data = im_data
@db_data = db_data
@to_update = []
@to_delete = []
end
def compare_values
if !im_data[:name].present?
@to_delete << im_data[:name]
elsif im_data[:name].present?
if im_data[:lookup].present? && (im_data[:lookup] != db_data.full_name)
@to_update << { id: im_data[:l_v_id], full_name: im_data[:lookup] }
elsif !im_data[:lookup].present? && (im_data[:name] != db_data.full_name)
@to_update << { id: im_data[:l_v_id], full_name: im_data[:name] }
end
end
end
end
后
def compare_values(im_data, db_data)
deselection(im_data)
re_apply(im_data, db_data)
end
def presence?(value)
value.present?
end
def deselection(im_data)
@to_delete << im_data[:l_v_id] unless presence?(im_data[:name])
end
def re_apply(im_data, db_data)
fv_present = presence?(im_data[:name])
compare_lookup(im_data, db_data.full_name) if fv_present
compare_name(im_data, db_data.full_name) if fv_present
end
def compare_lookup(im_data, l_value)
@to_update << { id: im_data[:l_v_id], full_name: im_data[:lookup] } if presence?(im_data[:lookup]) && (im_data[:lookup] != l_value)
end
def compare_name(im_data, full_name)
@to_update << { id: im_data[:l_v_id], full_name: im_data[:name] } if !presence?(im_data[:lookup]) && (im_data[:name] != full_name)
end
我试图遵循这个blog,但没有运气。我仍然觉得有更好的方法来重构这段代码。
答案 0 :(得分:1)
我个人发现&#34;&#34;&#34;更难以遵循。以下怎么样?
def compare_values
if @im_data[:name].present?
to_upd(@im_data[:lookup].present? ? :lookup : :name)
else
@to_delete << @im_data[:name]
end
end
def to_upd(key)
@to_update << { id: @im_data[:l_v_id], full_name: @im_data[key] } unless
@im_data[key] == @db_data.full_name
end