I have a Notification model which inherits from the ActiveRecord class. Each notification is associated with a specific type of action, which is determined by an integer field (action
) whose value is between 0 and 6. A notification is also associated with a model (e.g. User
or Project
) whose ID is stored as the object_id
field.
Inside a view, I am trying to prepare the notification text and url, which looks something like this:
# notif_string prepares the text of notification.
# For example: "username commented on"
= link_to(notif_string(notification) + notification.objectname,
notification.url)
The following methods in the Notification class where flagged as complex by Code Climate:
# Finds the object on which action is performed.
# Action can be of following types:
# 0: Commented on Project,
# 1: Followed Project,
# 2: Forked,
# 3: Followed User,
# 4: Created Project,
# 5: Commented on Issue
# 6: Created Issue
def objectname
case action
when 0
return Project.find(Comment.find(object_id).polycomment_id.to_i).name
when 5
return Issue.find(Comment.find(object_id).polycomment_id.to_i)
.friendly_text
when 3
return User.find(object_id).username
when 1, 2, 4
return Project.find(object_id).name
when 6
return Issue.find(object_id).friendly_text
end
end
# Find the url to which user which be directed when they click on the
# notification item
def url
case action
when 0
return Project.find(Comment.find(object_id).polycomment_id.to_i).urlbase
when 5
return Issue.find(Comment.find(object_id).polycomment_id.to_i).show_url
when 1, 2, 4
return Project.find(object_id).urlbase
when 6
return Issue.find(object_id).show_url
else
return "/#{actor.username}"
end
end
Yes, my cases are almost repeated but I am not sure how can reduce them. Most of the blogs suggest that I use polymorphism but again I don't know how I can apply it here.
action
a field ofNotification
? What does each of its possible values mean? What'sobjectname
for? \$\endgroup\$