-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathargraph
More file actions
executable file
·88 lines (72 loc) · 1.87 KB
/
argraph
File metadata and controls
executable file
·88 lines (72 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/env ruby
# ActiveRecord belongs_to graph generator (for rails apps)
# by tlehman
#
# If no args are given, all models are mapped out.
# Otherwise, the graph is restricted to the models given
# Example:
# $ argraph Author Post Comment
# digraph {
# Post -> Author
# Comment -> Post
# }
class Model < Struct.new(:filename, :modelname, :parents); end
def parents_of(filename)
lines = File.open(filename).readlines
parents = []
lines.grep(/belongs_to/).each do |line|
if /:class_name => .(?<other_model>([A-Z][a-z]*)+)./ =~ line
parents << other_model
else
/^\s*belongs_to :(?<other_model>[a-z_]+)/ =~ line
next unless other_model
parents << camel_case(other_model)
end
end
parents.uniq
end
def all_models
models = []
Dir["app/models/**/*.rb"].each do |filename|
file = File.open(filename)
contents = file.read
file.close
/class (?<modelname>([A-Z][a-z]*)+) < ActiveRecord::Base/ =~ contents
next unless modelname
models << Model.new(filename, modelname, parents_of(filename))
end
models
end
def camel_case(snake_case)
snake_case.split("_").map(&:capitalize).join
end
def print_as_digraph(models)
puts "digraph {"
models.each do |model|
model.parents.each do |parent|
puts " #{model.modelname} -> #{parent}"
end
end
puts "}"
end
def model_list_given?
return false if ARGV.empty?
ARGV.all? { |arg| arg.match(/([A-Z][a-z]+)/) }
end
def models_from_args
models = []
ARGV.each do |arg|
filename = `grep -r 'class #{arg} *<' app/models | awk -F: '{print $1}'`.strip
if filename == ""
STDERR.puts "Error: #{arg} is not a model"
next
end
models << Model.new(filename, arg, parents_of(filename) & ARGV)
end
models
end
def main
models = model_list_given? ? models_from_args : all_models
print_as_digraph(models)
end
main