Skip to content

Instantly share code, notes, and snippets.

@kakas
Created January 7, 2024 14:37
Show Gist options
  • Save kakas/c190e68142b0f3cb0cb5d0afe924502f to your computer and use it in GitHub Desktop.
Save kakas/c190e68142b0f3cb0cb5d0afe924502f to your computer and use it in GitHub Desktop.
class Student < ApplicationRecord
include LeadScoring::AttributeChangeListener
end
module LeadScoring
module AttributeChangeListener
extend ActiveSupport::Concern
included do
before_save :collect_changes_for_lead_scoring_notify
after_create_commit -> { notify_attributes_changes_for_lead_scoring(event: 'create') }
after_update_commit -> { notify_attributes_changes_for_lead_scoring(event: 'update') }
after_destroy_commit -> { notify_attributes_changes_for_lead_scoring(event: 'destroy') }
end
def collect_changes_for_lead_scoring_notify
@attributes_changes_for_lead_scoring ||= {}
@attributes_changes_for_lead_scoring = @attributes_changes_for_lead_scoring.merge(changes)
end
def notify_attributes_changes_for_lead_scoring(event:)
FactorCheckerMediator.new(
self,
changes: @attributes_changes_for_lead_scoring,
event: event,
).notify
@attributes_changes_for_lead_scoring = {}
end
end
end
module LeadScoring
class FactorCheckerMediator
ACTION_RECORD_CLASSES = [
# ...
]
SETTING_RECORD_CLASSES = [
# ...
]
MARK_RECORD_CLASSES = [
# ...
]
def initialize(record, changes:, event:)
@record = record
@changes = changes
@event = event
end
def notify
return if handler_klass.nil?
handler = handler_klass.new(@record, changes: @changes, event: @event)
handler.perform
end
private
def handler_klass
case @record
when Student, Alumnus
if @record.alumni?
"LeadScoring::ActionRecordChangeHandler::Alumnus".constantize
else
"LeadScoring::ActionRecordChangeHandler::Student".constantize
end
when *ACTION_RECORD_CLASSES
"LeadScoring::ActionRecordChangeHandler::#{@record.class.name}".constantize
when *SETTING_RECORD_CLASSES
"LeadScoring::SettingRecordChangeHandler::#{@record.class.name}".constantize
when *MARK_RECORD_CLASSES
"LeadScoring::MarkRecordChangeHandler::#{@record.class.name}".constantize
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment