Skip to content

Instantly share code, notes, and snippets.

@chrismcg
Created November 3, 2013 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrismcg/7294651 to your computer and use it in GitHub Desktop.
Save chrismcg/7294651 to your computer and use it in GitHub Desktop.
Playing with TracePoint and PlantUML Sequence Diagrams.
class Worker
def actually_do_work
puts "workin!"
end
end
class Bar
def nope_maybe_this_does(worker = Worker)
worker.new.actually_do_work
worker.new.actually_do_work
end
end
class Foo
def does_this_do_any_work(barrer = Bar)
b = barrer.new
b.nope_maybe_this_does
b.nope_maybe_this_does
end
end
Call = Struct.new(:caller, :callee, :method) do
def direction
"->"
end
end
Return = Struct.new(:caller, :callee, :method) do
def direction
"<--"
end
end
class System; end
stack = []
actors = { System.new => true }
sequence = []
calls = TracePoint.new(:call) do |tp|
actors[tp.self] = true
call = Call.new(tp.defined_class, tp.defined_class, tp.method_id)
stack.push(call)
sequence << call
end
returns= TracePoint.new(:return) do |tp|
actors[tp.self] = true
the_caller = stack[-2]
stack.pop.caller = the_caller ? the_caller.caller : System
end
[calls, returns].each(&:enable)
Foo.new.does_this_do_any_work
[calls, returns].each(&:disable)
puts stack
output = []
output << "@startuml"
actors.map { |object, _| object.class }.uniq.each do |object_class|
output << %(participant #{object_class})
end
sequence.each do |call|
output << "#{call.caller} #{call.direction} #{call.callee}: #{call.method}" if call.is_a? Call
end
output << "@enduml"
File.write "tmp.plantuml", output.join("\n")
@startuml
participant System
participant Foo
participant Bar
participant Worker
System -> Foo: does_this_do_any_work
Foo -> Bar: nope_maybe_this_does
Bar -> Worker: actually_do_work
Bar -> Worker: actually_do_work
Foo -> Bar: nope_maybe_this_does
Bar -> Worker: actually_do_work
Bar -> Worker: actually_do_work
@enduml
@chrismcg
Copy link
Author

chrismcg commented Nov 3, 2013

Generates:

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