Class: Groundskeeper::Document

Inherits:
Object
  • Object
show all
Defined in:
lib/groundskeeper/document.rb

Overview

Wraps files.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Document

Returns a new instance of Document.



8
9
10
# File 'lib/groundskeeper/document.rb', line 8

def initialize(path)
  @path = File.expand_path(path)
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



6
7
8
# File 'lib/groundskeeper/document.rb', line 6

def path
  @path
end

Instance Method Details

#append_to_file(expression, value) ⇒ Object

Inserts the provided value after the expression in place in the file.



40
41
42
43
44
45
# File 'lib/groundskeeper/document.rb', line 40

def append_to_file(expression, value)
  content = read.force_encoding("utf-8")
  match = content.match(expression)[0].force_encoding("utf-8")
  content.gsub! expression, match + value
  write_file content
end

#exists?Boolean

Returns:

  • (Boolean)


12
13
14
# File 'lib/groundskeeper/document.rb', line 12

def exists?
  File.exist?(path)
end

#file?Boolean

Returns:

  • (Boolean)


16
17
18
# File 'lib/groundskeeper/document.rb', line 16

def file?
  File.file?(path)
end

#gsub_file(expression, value) ⇒ Object

Replaces the expression with the provided value in place in the file.



33
34
35
36
37
# File 'lib/groundskeeper/document.rb', line 33

def gsub_file(expression, value)
  content = read
  content.gsub! expression, value
  write_file content
end

#make_parent_directory!Object



20
21
22
# File 'lib/groundskeeper/document.rb', line 20

def make_parent_directory!
  Dir.mkdir(File.dirname(path))
end

#match(expression_with_capture) ⇒ Object

Returns the first captured expression or nil if it is not found.



25
26
27
28
29
30
# File 'lib/groundskeeper/document.rb', line 25

def match(expression_with_capture)
  content = read
  match = content.match(expression_with_capture)

  match[1] if match
end

#prepend_file(value) ⇒ Object

Inserts the provided value at the beginning of the file.



48
49
50
51
# File 'lib/groundskeeper/document.rb', line 48

def prepend_file(value)
  content = read
  write_file(value + content)
end

#readObject



57
58
59
60
61
# File 'lib/groundskeeper/document.rb', line 57

def read
  return "" unless exists? && file?

  File.binread(path)
end

#write_file(content) ⇒ Object



53
54
55
# File 'lib/groundskeeper/document.rb', line 53

def write_file(content)
  File.binwrite(path, content)
end