Class: Umlify::Parser

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

Overview

First version of the ruby parser, using regular expression. Parser is responsible for parsing ruby source files and building an array of uml classes

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(files) ⇒ Parser

files should be an array containing file names with the correct path



13
14
15
16
# File 'lib/umlify/parser.rb', line 13

def initialize files
  @files = files
  @classes = []
end

Instance Attribute Details

#classesObject

An array containing all the parsed classes type: UmlClass



10
11
12
# File 'lib/umlify/parser.rb', line 10

def classes
  @classes
end

Instance Method Details

#parse_file(file) ⇒ Object

Parse the given file or string, and return the parsed classes



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
# File 'lib/umlify/parser.rb', line 38

def parse_file file
  classes_in_file = []
  current_class = nil
  type_annotation = nil

  file.each do |line|

    # This parses the classes
    line.match(/^\s*class ([\w]*)\b[\s]*$/) do |m|
      current_class = UmlClass.new m[1]
      classes_in_file << current_class
    end

    # This parses the classes and its parent (class Foo < Bar)
    line.match(/^\s*class ([\w]*) < ([\w]*)\b/) do |m|
      current_class = UmlClass.new m[1]
      current_class.parent = m[2]
      classes_in_file << current_class
    end

    if current_class

      # This parses the @variables
      line.match(/@([\w]*)\b/) do |m|
        current_class.variables << m[1] unless current_class.variables.include? m[1]
      end

      # This parses the methods
      line.match(/def ([\w]*)\b/) do |m|
        current_class.methods << m[1] unless current_class.methods.include? m[1]
      end

      # This raises the type_annotation flag
      line.match(/# type: ([\w]*)\b/) {|m| type_annotation = m[1]}

      # This adds an association to the current class, using the type_annotation
      # if type_annotation has been set
      line.match(/(attr_accessor|attr_reader|attr_writer) :([\w]*)\b/) do |m|
        current_class.associations[m[2]] = type_annotation
        type_annotation = nil
      end if type_annotation

    end
  end

  classes_in_file
end

#parse_sources!Object

Parses the source code of the files in @files to build uml classes. Returns an array containing all the parsed classes or nil if no ruby file were found in the



22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/umlify/parser.rb', line 22

def parse_sources!

  @source_files = @files.select {|f| f.match /\.rb/}
  return nil if @source_files.empty?

  @source_files.each do |file|
    puts "processing #{file}..."
    f = File.open file, 'r'
    (parse_file f).each {|c| @classes << c}
    f.close
  end

  @classes
end