forked from beautyjoy/BJC-Teacher-Tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Refactored merge controller through merge_service
- Loading branch information
Showing
2 changed files
with
41 additions
and
36 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
# frozen_string_literal: true | ||
|
||
class MergeService | ||
# Returns a new Teacher object with merged attributes but does not save it | ||
def self.get_merged_teacher(from_teacher, into_teacher) | ||
merged_attributes = get_merged_attributes(from_teacher, into_teacher) | ||
Teacher.new(merged_attributes) | ||
end | ||
|
||
# Returns the merged attributes hash excluding the "id" attribute | ||
def self.get_merged_attributes(from_teacher, into_teacher) | ||
merged_attributes = {} | ||
into_teacher.attributes.each do |attr_name, attr_value| | ||
next if attr_name == "id" | ||
|
||
from_teacher_attr_value = from_teacher.attributes[attr_name] | ||
if attr_value.blank? | ||
merged_attributes[attr_name] = from_teacher_attr_value | ||
elsif from_teacher_attr_value.blank? | ||
merged_attributes[attr_name] = attr_value | ||
else | ||
case attr_name | ||
when "session_count" | ||
merged_attributes[attr_name] = attr_value + from_teacher_attr_value | ||
when "ip_history" | ||
merged_attributes[attr_name] = (attr_value + from_teacher_attr_value).uniq | ||
when "last_session_at" | ||
merged_attributes[attr_name] = [attr_value, from_teacher_attr_value].max | ||
when "created_at" | ||
merged_attributes[attr_name] = [attr_value, from_teacher_attr_value].min | ||
else | ||
merged_attributes[attr_name] = attr_value | ||
end | ||
end | ||
end | ||
|
||
merged_attributes | ||
end | ||
end |