Sha256: 802967f0d893a64a9ce82a2f1d071736fe846dbbcb441eefd0cc24dbf4d626a6

Contents?: true

Size: 1.72 KB

Versions: 4

Compression:

Stored size: 1.72 KB

Contents

module NxtStateMachine
  class Graph
    def initialize(state_machines, **options)
      @state_machines = state_machines
      @options = default_options.merge(**options)
    end

    def draw
      require 'ruby-graphviz'

      state_machines.each do |_, state_machine|
        add_nodes(state_machine)
        add_edges(state_machine)
      end

      filename = File.join(options[:path], "#{options[:name]}.#{options[:format]}")

      graph.output options[:format] => filename

      puts '----------------------------------------------'
      puts 'Please run the following to open the generated file:'
      puts "open '#{filename}'"
      puts '----------------------------------------------'

      graph
    end

    private

    attr_reader :options, :state_machines

    def graph
      @graph ||= ::GraphViz.new(
        'G',
        rankdir: options[:orientation] == 'landscape' ? 'LR' : 'TB',
        ratio: options[:ratio]
      )
    end

    def add_nodes(state_machine)
      state_machine.states.values.each do |state|
        add_node(state)
      end
    end

    def add_node(state)
      node_options = {
        label: state.to_s,
        width: '1',
        height: '1',
        shape: 'ellipse'
      }

      graph.add_nodes(state.to_s, node_options)
    end

    def add_edges(state_machine)
      state_machine.events.values.each do |event|
        event.event_transitions.values.each do |transition|
          graph.add_edges(transition.from.to_s, transition.to.to_s, label: event.name)
        end
      end
    end

    def default_options
      {
        name: 'state_machine',
        path: '.',
        orientation: 'landscape',
        ratio: 'fill',
        format: 'png',
        font: 'Helvetica'
      }
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
nxt_state_machine-0.1.12 lib/nxt_state_machine/graph.rb
nxt_state_machine-0.1.11 lib/nxt_state_machine/graph.rb
nxt_state_machine-0.1.10 lib/nxt_state_machine/graph.rb
nxt_state_machine-0.1.9 lib/nxt_state_machine/graph.rb