Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pluggable event tracking for start_conversation and state transitions #70

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/socrates/configuration.rb
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ class Configuration
attr_accessor :logger
attr_accessor :error_handler # a callable like ->(String, Exception) { ... }
attr_accessor :warn_handler # a callable like ->(String) { ... }
attr_accessor :event_handler # a callable like ->(Session, Event, Data) { ... }

def initialize
@storage = Storage::Memory.new
Expand All @@ -27,6 +28,9 @@ def initialize
@logger = Socrates::Logger.default
@error_handler = proc { |_message, _error| }
@warn_handler = proc { |_message| }
@event_handler = proc { |_session, event, data|
puts ">>> #{event}: #{data.inspect}"
}
end
end
end
5 changes: 5 additions & 0 deletions lib/socrates/core/dispatcher.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ def initialize(adapter:, state_factory:, storage: nil)
@logger = Socrates.config.logger
@error_handler = Socrates.config.error_handler
@error_message = Socrates.config.error_message || DEFAULT_ERROR_MESSAGE
@event_handler = Socrates.config.event_handler
end

def dispatch(message, context: {})
Expand Down Expand Up @@ -49,6 +50,8 @@ def start_conversation(user, state_id, message: nil)
# Send our initial message if one was passed to us.
@adapter.queue_direct_message(session, message, user) if message.present?

@event_handler.call(session, :start_conversation, state: state_id, msg: message)

do_dispatch(session, nil)
true
end
Expand Down Expand Up @@ -94,6 +97,8 @@ def do_dispatch(session, message)
return
end

@event_handler.call(session, :transition, msg: message, from: state.data.state_id, to: state.next_state_id)

# Update the persisted state data so we know what to run next time.
state.data.state_id = state.next_state_id
state.data.state_action = state.next_state_action
Expand Down