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
33
34
35
36
37
# File 'lib/active_record/annotate/file.rb', line 12

def annotate_with(annotation, configurator)
  magic_comments = []
  while @lines.first =~ /^\s*#.*(coding|frozen_string_literal|warn_indent)/i
    magic_comments.push(@lines.shift)
  end

  unless magic_comments.empty?
    # separate magic comments from the annotation with an empty line
    magic_comments << nil
  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(*magic_comments)
  @lines.push(nil) # newline at the end of file
end

#changed?Boolean

Returns:

  • (Boolean)


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

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

#relative_pathObject



55
56
57
# File 'lib/active_record/annotate/file.rb', line 55

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

#writeObject



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/active_record/annotate/file.rb', line 39

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