Last active
April 27, 2017 15:18
-
-
Save ryenski/de7e9108910c2cf1a8b605c1ddc8e6cd to your computer and use it in GitHub Desktop.
A service object that takes a trackable object, action, and parameters, and creates an Activity record for action auditing.
This file contains hidden or 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
class ActivityCreator | |
def initialize(action, trackable, contact, comment=nil) | |
@trackable = trackable # the affected object (could be the same as contact) | |
@action = action # what was done | |
@comment = comment | |
@changes = collect_changes | |
end | |
def call | |
attrs = { | |
tenant_id: Tenant.current_id, | |
user_id: User.current_id, | |
trackable: trackable, | |
action: action, | |
tracked_changes: changes | |
} | |
unless changes.empty? && action == 'update' | |
Activity.create!(attrs) | |
end | |
end | |
attr_accessor :user, :action, :trackable, :contact, :comment, :changes | |
private | |
IGNORE_ATTRS = [ | |
:created_at, | |
:password_digest, | |
:registration_token, | |
:auth_token, | |
:tenant_id, | |
:updated_at, | |
] | |
def remove_empty(changes) | |
changes.delete_if{|k,v| v[0].blank? and v[1].blank?} | |
end | |
def collect_changes | |
if action == 'create' | |
IGNORE_ATTRS.push(:id) | |
end | |
changes = trackable.previous_changes.except(*IGNORE_ATTRS) | |
changes = remove_empty(changes) | |
changes = changes | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment