Skip to content

Instantly share code, notes, and snippets.

@ToJans
Last active December 21, 2015 07:08
Show Gist options
  • Save ToJans/6269026 to your computer and use it in GitHub Desktop.
Save ToJans/6269026 to your computer and use it in GitHub Desktop.
An attempt for a more succint event handler in elixir
defmodule Listen.NewFSM do
use OtpDsl.Genfsm, register: {:local, :listen_fsm},
initial_state: :start,
init_params: []
@timeout 3*1000
defrecord CallInfo, from: "", to: "", suspicious_segments: 0
defstate start do
defhandler call_initiated(from,to) do
IO.puts "Initiating a call from #{from} to #{to}"
emit listening(CallInfo.new(from: from, to: to))
end
end
defstate listening do
defhandler hang_up do
debug("Hangup", context)
emit start
end
defhandler suspicious_phrase_heard do
debug("Heard something suspicious", context)
emit transcribing(context.update_suspicious_segments(&1+1), @timeout)
end
end
defstate transcribing do
defhandler hang_up do
debug("Report on call", context)
emit start(CallData.new)
end
defhandlerp timeout do
emit listening(context)
end
end
# Helpers
defp debug(msg, CallInfo[from: from, to: to, suspicious_segments: suspicious_segments]) do
IO.puts("Call from #{from} to #{to}: #{msg}")
if suspicious_segments > 0 do
IO.puts(" (suspicious_segments: #{suspicious_segments})")
end
end
end
@ToJans
Copy link
Author

ToJans commented Aug 19, 2013

Added the emitkeyword to emit state transitions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment