Class: ModelParser

Inherits:
Object
  • Object
show all
Defined in:
lib/model-visualizer/model-parser.rb

Instance Method Summary collapse

Constructor Details

#initialize(models) ⇒ ModelParser

Returns a new instance of ModelParser.



7
8
9
# File 'lib/model-visualizer/model-parser.rb', line 7

def initialize(models)
    @models = models
end

Instance Method Details

#fix_case(string) ⇒ Object



53
54
55
# File 'lib/model-visualizer/model-parser.rb', line 53

def fix_case(string)
    ActiveSupport::Inflector.singularize(ActiveSupport::Inflector.camelize(string))
end

#parse(root) ⇒ Object



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
# File 'lib/model-visualizer/model-parser.rb', line 11

def parse(root)
    unless Dir.exists? File.join(root, 'app/models/')
        abort 'app/models/ directory does not exist! Run from or pass the root directory of your Rails project.'
    end

    files = Dir[File.join(root, 'app/models/**/*.rb')]
    curr_model = nil

    # TODO: maybe factor this out into a parent class?
    for file in files
        IO.foreach(file) do |line|
            # TODO: hack to skip associations, we need to display these as "has_many: Users AS Managers"
            if line.include? 'class_name'
                next
            end

            line.strip!
            if !(/^class ([[:alpha:]]+) < ActiveRecord::Base/.match(line)).nil?
                name = /^class ([[:alpha:]]+) < ActiveRecord::Base/.match(line)[1] 
                curr_model = Model.new(name)
                @models[name] = curr_model

            elsif !(/^has_many :(\w+)/.match(line)).nil?
                model_neighbor = /^has_many :(\w+)/.match(line)[1]
                curr_model.add_has_many fix_case(model_neighbor)

            elsif !(/^has_one :(\w+)/.match(line)).nil?
                model_neighbor = /^has_one :(\w+)/.match(line)[1]
                curr_model.add_has_one fix_case(model_neighbor)

            elsif !(/^has_and_belongs_to_many :(\w+)/.match(line)).nil?
                model_neighbor = /^has_and_belongs_to_many :(\w+)/.match(line)[1]
                curr_model.add_has_and_belongs_to_many fix_case(model_neighbor)

            elsif !(/^belongs_to :(\w+)/.match(line)).nil?
                model_neighbor = /^belongs_to :(\w+)/.match(line)[1]
                curr_model.add_belongs_to fix_case(model_neighbor)
            end
        end
    end
end