Class: Annotator::Attributes

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

Overview

Attributes within given model file

Constant Summary collapse

R_ATTRIBUTE =
/^# \* (\w+) \[(.*?)\]( \- )?(.*)$/
R_ATTRIBUTE_NEXT_LINE =
/^#   (.*?)$/
R_ATTRIBUTE_LINE =
/(#{R_ATTRIBUTE})|(#{R_ATTRIBUTE_NEXT_LINE})/
HEADER =
"# Attributes:"
MAX_CHARS_PER_LINE =
120

Instance Method Summary collapse

Constructor Details

#initialize(model, lines) ⇒ Attributes

Returns a new instance of Attributes.



11
12
13
14
15
16
17
# File 'lib/annotator/attributes.rb', line 11

def initialize(model, lines)
  @model = model
  @lines = lines
  @attrs = []
  @changes = []
  parse
end

Instance Method Details

#linesObject

Convert attributes array back to attributes lines representation to be put into file



20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/annotator/attributes.rb', line 20

def lines
  ret = [Attributes::HEADER]
  # Sort by name, but id goes first
  @attrs.sort_by{|x| x[:name] == 'id' ? '_' : x[:name]}.each do |row|
    line = "# * #{row[:name]} [#{row[:type]}]#{row[:desc].to_s.empty? ? "" : " - #{row[:desc]}"}"
    # split into lines that don't exceed 80 chars
    lt = wrap_text(line, MAX_CHARS_PER_LINE-3).split("\n")
    line = ([lt[0]] + lt[1..-1].map{|x| "#   #{x}"}).join("\n")
    ret << line
  end
  ret
end

#update!Object

Update attribudes array to the current database state



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
# File 'lib/annotator/attributes.rb', line 34

def update!
  @model.columns.each do |column|
    if row = @attrs.find {|x| x[:name] == column.name}
      if row[:type] != type_str(column)
        puts "  M #{@model}##{column.name} [#{row[:type]} -> #{type_str(column)}]"
        row[:type] = type_str(column)
      elsif row[:desc] == InitialDescription::DEFAULT_DESCRIPTION
        new_desc = InitialDescription.for(@model, column.name)
        if row[:desc] != new_desc
          puts "  M #{@model}##{column.name} description updated"
          row[:desc] = new_desc
        end
      end
    else
      puts "  A #{@model}##{column.name} [#{type_str(column)}]"
      @attrs << {
        :name => column.name,
        :type => type_str(column),
        :desc => InitialDescription.for(@model, column.name)
      }
    end
  end

  # find columns that no more exist in db
  orphans = @attrs.map{|x| x[:name]} - @model.columns.map(&:name)
  unless orphans.empty?
    orphans.each do |orphan|
      puts "  D #{@model}##{orphan}"
      @attrs = @attrs.select {|x| x[:name] != orphan}
    end
  end

  @attrs
end