Class: Annotator::Model

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

Overview

Represents a single model file and associated class

Instance Method Summary collapse

Constructor Details

#initialize(filename, base_path) ⇒ Model

Returns a new instance of Model.



6
7
8
9
10
# File 'lib/annotator/model.rb', line 6

def initialize(filename, base_path)
  @filename = filename
  @base_path = base_path
  @blocks = Hash.new {[]}
end

Instance Method Details

#klassObject

Model class



13
14
15
16
17
18
19
# File 'lib/annotator/model.rb', line 13

def klass
  begin 
    @filename.split(@base_path).last.split(/\.rb$/).first.camelize.constantize rescue nil
  rescue Exception
    nil
  end
end

#parseObject

Split file into 3 blocks: before attributes, attributes block, and after If there’s no attributes block, content will be in :after part (for easier insertion)



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

def parse
  @file = File.read(@filename).strip
  current_block = :before
  return @nodoc = true if @file.match(/^# Attributes\(nodoc\):$/i)
  @file.split("\n").each do |line|
    if line.match(/^#{Regexp.escape Attributes::HEADER} *$/)
      current_block = :attributes
      next
    end
    current_block = :after if current_block == :attributes && !line.match(Attributes::R_ATTRIBUTE_LINE)
    @blocks[current_block] += [line]
  end


  # If there is no after block, it means there are no attributes block yet.
  # Let's try to find some good place to insert them.
  if @blocks[:after].empty?
    @blocks[:before].each_with_index do |line,i|
      # We want to insert them after requires or any comment block at the beginning of the file
      unless line.match(/^require/) || line.match(/^#/)
        @blocks[:after] = @blocks[:before][i..-1]
        @blocks[:before] = (i == 0) ? [] : @blocks[:before][0..(i-1)] + [''] # add one additional separation line to make it cleaner
        break
      end
    end
  end

end

#skipped?Boolean

If this file does not have associated AR class it should be skipped

Returns:

  • (Boolean)


53
54
55
# File 'lib/annotator/model.rb', line 53

def skipped?
  !klass || !klass.ancestors.include?(ActiveRecord::Base) || @nodoc
end

#update!Object

Update file with new database information



64
65
66
67
68
69
70
71
# File 'lib/annotator/model.rb', line 64

def update!
  parse
  return true if skipped?
  attributes = Attributes.new klass, @blocks[:attributes]
  attributes.update!
  @blocks[:attributes] = attributes.lines
  update_file
end

#update_fileObject

Save changes to file if there were any



58
59
60
61
# File 'lib/annotator/model.rb', line 58

def update_file
  output = (@blocks[:before] + @blocks[:attributes] + @blocks[:after]).join("\n").strip + "\n"
  File.open(@filename,'w') { |f| f.write(output) } if output != @file
end