Class: RailsErdD3

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_erd_d3.rb

Class Method Summary collapse

Class Method Details

.create_erd ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/rails_erd_d3.rb', line 46

def self.create_erd
  file = File.new("erd.html", "w")
  file.puts("
    <!DOCTYPE HTML>
    <html>
      #{get_head}
      <body>
        #{get_nav}
        <div id='erd'>
        </div>
        #{get_d3}
        #{get_modals}
      </body>
    </html>
  ")
  file.close
end

.get_all_models ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/rails_erd_d3.rb', line 8

def self.get_all_models
  version = get_rails_version

  case get_rails_version
  when 4
    klass = ActiveRecord::Base
  when 5
    klass = ApplicationRecord
  end

  Rails.application.eager_load!
  @@models = ObjectSpace.each_object(Class).select { |o| o.superclass == klass } || []
end

.get_d3 ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/rails_erd_d3.rb', line 91

def self.get_d3
  "<script>
    var data = #{get_data};

    var width = window.innerWidth
      || document.documentElement.clientWidth
      || document.body.clientWidth;
    var height = window.innerHeight
      || document.documentElement.clientHeight
      || document.body.clientHeight;

    var colorScale = d3.scaleOrdinal(d3.schemeCategory20);

    var svg = d3.select('#erd').append('svg')
      .attr('height', height)
      .attr('width', width)
      .style('background', 'white');

    var simulation = d3.forceSimulation()
      .force('link', d3.forceLink().id(function(d) { return d.index }))
      .force('collide',d3.forceCollide( function(d){return d.r + 20 }).iterations(30) )
      .force('charge', d3.forceManyBody())
      .force('center', d3.forceCenter(width / 2, height / 2))
      .force('y', d3.forceY(0))
      .force('x', d3.forceX(0));

    var link = svg.append('g')
      .classed('links', true)
      .selectAll('line')
      .data(data.links)
      .enter()
      .append('line')
      .attr('stroke', 'black');

    var node = svg.selectAll('.node')
      .data(data.nodes)
      .enter()
      .append('g')
      .classed('node', true)
      .style('cursor', 'pointer')
      .attr('data-toggle', 'modal')
      .attr('data-target', function(d, i){ return '#' + data.nodes[i].label })
      .call(d3.drag()
        .on('start', dragstarted)
        .on('drag', dragged)
        .on('end', dragended));

    node.append('circle')
      .classed('circle', true)
      .attr('r', function(d){  return d.r })
      .attr('fill', function(d, i){ return colorScale(i) });

    node.append('text')
      .classed('text', true)
      .text(function(d) {
        return d.label;
      });

    var ticked = function() {
        link
          .attr('x1', function(d) { return d.source.x; })
          .attr('y1', function(d) { return d.source.y; })
          .attr('x2', function(d) { return d.target.x; })
          .attr('y2', function(d) { return d.target.y; });

        node
          .attr('transform', function(d) {
            return 'translate(' + [d.x, d.y] + ')';
          });
    }

    simulation
        .nodes(data.nodes)
        .on('tick', ticked);

    simulation.force('link')
        .links(data.links);

    function dragstarted(d) {
        if (!d3.event.active) simulation.alphaTarget(0.3).restart();
        d.fx = d.x;
        d.fy = d.y;
    }

    function dragged(d) {
        d.fx = d3.event.x;
        d.fy = d3.event.y;
    }

    function dragended(d) {
        if (!d3.event.active) simulation.alphaTarget(0);
        d.fx = null;
        d.fy = null;
    }
  </script>"
end

.get_data ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/rails_erd_d3.rb', line 22

def self.get_data
  get_all_models

  nodes = []
  links = []
  models_list = {}

  @@models.each_with_index do |model, index|
    models_list[model.name] = index
  end

  @@models.each_with_index do |model, index|
    name = model.name.capitalize

    nodes << { label: name, r: 30 }
    model.reflections.keys.each do |key|
      links << { source: models_list[name], target: models_list[key.capitalize] }
    end
  end

  data = { nodes: nodes, links: links }
  data.to_json
end

.get_head ⇒ Object



66
67
68
69
70
71
72
73
74
75
# File 'lib/rails_erd_d3.rb', line 66

def self.get_head
  "<head>
    <title>ERD</title>
    <meta charset='utf-8'>
    <script   src='https://code.jquery.com/jquery-3.1.1.min.js' integrity='sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=' crossorigin='anonymous'></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.min.js'></script>
    <script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js' integrity='sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa' crossorigin='anonymous'></script>
    <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' integrity='sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u' crossorigin='anonymous'>
  </head>"
end

.get_modals ⇒ Object



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/rails_erd_d3.rb', line 188

def self.get_modals
  modals = ""
  @@models.each do |model|
    modals += "<div class='modal fade' id='#{model.name.capitalize}' tabindex='-1' role='dialog'>
                <div class='modal-dialog' role='document'>
                  <div class='modal-content'>
                    <div class='modal-header'>
                      <button type='button' class='close' data-dismiss='modal' aria-label='Close'><span aria-hidden='true'>&times;</span></button>
                      <h4 class='modal-title'>#{model.name.capitalize}</h4>
                    </div>
                    <div class='modal-body'>
                    <table class='table table-hover'>
                      <thead>
                        <tr>
                          <th>#</th>
                          <th>name</th>
                          <th>macro</th>
                          <th>foreign_key</th>
                        </tr>
                      </thead>
                      <tbody>"

    model.reflections.each_with_index do |r, index|
      name = r[0]
      modals += "<tr>"\
                  "<th>#{index + 1}</th>"\
                  "<td>#{name.capitalize}</td>"\
                  "<td>#{model.reflections[name].macro}</td>"\
                  "<td>#{model.reflections[name].foreign_key}</td>"\
                "</tr>"
    end

    modals += "</tbody>
              </table>
            </div>
            <div class='modal-footer'>
              <button type='button' class='btn btn-default' data-dismiss='modal'>Close</button>
            </div>
          </div>
        </div>
      </div>"
  end

  modals
end

.get_nav ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/rails_erd_d3.rb', line 77

def self.get_nav
  "<nav class='navbar navbar-default'>
    <div class='container-fluid'>
      <div class='navbar-header'>
        <div class='navbar-brand'>
          <a href='https://github.com/RomanKrasavtsev/rails-erd-d3'>
            Rails-ERD-D3
          </a>
        </div>
      </div>
    </div>
  </nav>"
end

.get_rails_version ⇒ Object



4
5
6
# File 'lib/rails_erd_d3.rb', line 4

def self.get_rails_version
  Rails::VERSION::MAJOR
end