Created
September 16, 2013 02:35
-
-
Save jordanmaguire/6576135 to your computer and use it in GitHub Desktop.
ERDBuilder using mother flipping ruby-graphviz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'graphviz' | |
class ERDBuilder | |
attr_reader :name | |
def add_entity(name) | |
ERDEntity.new.tap do |entity| | |
entity.build(graph: graph, name: name) | |
end | |
end | |
def associate(entity, other_entity, attributes) | |
diagram.add_edges(entity.name, other_entity.name, edge_attributes_for(attributes)) | |
end | |
def begin_system(name) | |
@name = name | |
# Initialize these objects | |
diagram | |
graph | |
end | |
def export_as_png | |
diagram.output(png: "#{name}.png") | |
end | |
private | |
def diagram | |
@diagram ||= GraphViz.digraph(name) do |graph_models_diagram| | |
graph_models_diagram[:overlap] = 'false' | |
graph_models_diagram[:splines] = 'true' | |
end | |
end | |
def edge_attributes_for(attributes) | |
case attributes[:association] | |
when :many_to_one | |
arrowhead = 'crow' | |
arrowtail = 'odot' | |
else | |
arrowhead = 'odot' | |
arrowtail = 'odot' | |
end | |
label = attributes[:name] || "Label" | |
{ | |
arrowhead: arrowhead, | |
arrowtail: arrowtail, | |
dir: 'both', | |
label: label | |
} | |
end | |
def graph | |
@graph ||= @diagram.add_graph(name).tap do |graph| | |
graph[:overlap] = 'false' | |
graph[:rank] = 'same' | |
graph[:splines] = 'true' | |
end | |
end | |
end | |
class ERDEntity | |
attr_reader :name | |
def attributes=(attributes) | |
attributes_as_string = attributes.collect do |key, value| | |
"#{key} :#{value}" | |
end.join('\l') | |
@node.label = "{#{name}| #{attributes_as_string}}" | |
end | |
def build(attributes) | |
@graph = attributes[:graph] | |
@name = attributes[:name] | |
@node = @graph.add_nodes(name, shape: 'record') | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment