Refactoring: Rearrange CanCreatesAndUpdates concern

This commit is contained in:
Ryan Lue 2019-03-14 19:03:44 +08:00 committed by Thorsten Eckel
parent 134dde5567
commit 03a6077e76

View file

@ -25,7 +25,7 @@ returns
=begin =begin
Model.create_or_update with ref lookups create or update model (check exists based on id, name, login, email or locale)
result = Model.create_or_update(attributes) result = Model.create_or_update(attributes)
@ -35,9 +35,13 @@ returns
=end =end
def create_or_update_with_ref(data) def create_or_update(data)
data = association_name_to_id_convert(data) attr = (data.keys & %i[id name login email locale]).first
create_or_update(data)
raise ArgumentError, 'Need name, login, email or locale for create_or_update()' if attr.nil?
record = case_sensitive_find_by(data.slice(attr))
record.nil? ? create(data) : record.tap { |r| r.update(data) }
end end
=begin =begin
@ -59,7 +63,7 @@ returns
=begin =begin
create or update model (check exists based on id, name, login, email or locale) Model.create_or_update with ref lookups
result = Model.create_or_update(attributes) result = Model.create_or_update(attributes)
@ -69,13 +73,9 @@ returns
=end =end
def create_or_update(data) def create_or_update_with_ref(data)
attr = (data.keys & %i[id name login email locale]).first data = association_name_to_id_convert(data)
create_or_update(data)
raise ArgumentError, 'Need name, login, email or locale for create_or_update()' if attr.nil?
record = case_sensitive_find_by(data.slice(attr))
record.nil? ? create(data) : record.tap { |r| r.update(data) }
end end
def case_sensitive_find_by(**attrs) def case_sensitive_find_by(**attrs)