Class: ActiveRecord::Annotate::File

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record/annotate/file.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ File

Returns a new instance of File.



6
7
8
9
10
# File 'lib/active_record/annotate/file.rb', line 6

def initialize(path)
  @path    = path
  @content = ::File.read(path)
  @lines   = @content.split(?\n)
end

Instance Attribute Details

#linesObject (readonly)

Returns the value of attribute lines.



4
5
6
# File 'lib/active_record/annotate/file.rb', line 4

def lines
  @lines
end

#pathObject (readonly)

Returns the value of attribute path.



4
5
6
# File 'lib/active_record/annotate/file.rb', line 4

def path
  @path
end

Instance Method Details

#annotate_with(annotation, configurator) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/active_record/annotate/file.rb', line 12

def annotate_with(annotation, configurator)
  if @lines.first =~ /^\s*#.*coding/
    # encoding: utf-8 encountered on the first line
    encoding_line = @lines.shift
  end
  
  while @lines.first.start_with?('#') || @lines.first.blank?
    # throw out comments and empty lines
    # in the beginning of the file (old annotation)
    @lines.shift
  end
  
  if configurator.yard?
    backticks = '# ```'
    annotation.unshift(backticks).push(backticks)
  end
  
  @lines.unshift(*annotation, nil)
  @lines.unshift(encoding_line) unless encoding_line.nil?
  @lines.push(nil) # newline at the end of file
end

#changed?Boolean

Returns:

  • (Boolean)


46
47
48
# File 'lib/active_record/annotate/file.rb', line 46

def changed?
  @lines.join(?\n) != @content
end

#relative_pathObject



50
51
52
# File 'lib/active_record/annotate/file.rb', line 50

def relative_path
  path.sub(/^#{Rails.root}\//, '')
end

#writeObject



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/active_record/annotate/file.rb', line 34

def write
  new_file_content = @lines.join(?\n)
  temp_path = "#{@path}.annotated"
  
  ::File.open(temp_path, 'w') do |temp_file|
    temp_file.write(new_file_content)
  end
  
  ::File.delete(@path)
  ::File.rename(temp_path, @path)
end