Class: Ghost::TokenizedFile

Inherits:
Object
  • Object
show all
Defined in:
lib/ghost/tokenized_file.rb

Overview

TODO: make it not necessarily line-based tokenization TODO: make it delegate or inherit from File/IO/StringIO to allow it to be a

drop-in to things expecting an IO.
  - Allow consumer to manipulate a real IO, and sync the contents
    into the real file between the tokens?

TODO: make this it’s own gem/library. This has nothing to do (specifically)

with hosts file management

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, start_token, end_token) ⇒ TokenizedFile

Returns a new instance of TokenizedFile.



12
13
14
15
16
# File 'lib/ghost/tokenized_file.rb', line 12

def initialize(path, start_token, end_token)
  self.path        = path
  self.start_token = start_token
  self.end_token   = end_token
end

Instance Attribute Details

#end_tokenObject

Returns the value of attribute end_token.



10
11
12
# File 'lib/ghost/tokenized_file.rb', line 10

def end_token
  @end_token
end

#pathObject

Returns the value of attribute path.



10
11
12
# File 'lib/ghost/tokenized_file.rb', line 10

def path
  @path
end

#start_tokenObject

Returns the value of attribute start_token.



10
11
12
# File 'lib/ghost/tokenized_file.rb', line 10

def start_token
  @start_token
end

Instance Method Details

#readObject



18
19
20
# File 'lib/ghost/tokenized_file.rb', line 18

def read
  read_capturing
end

#write(content) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/ghost/tokenized_file.rb', line 22

def write(content)
  existing_lines = []

  # TODO: how to do this without closing the file so
  #       we can reopen with write mode and maintain a
  #       lock
  read_capturing { |line| existing_lines << line}

  # TODO: lock file
  File.open(path, 'w') do |file|
    file.puts(existing_lines)

    unless content.nil? || content.empty?
      file.puts(start_token)
      file.puts(content)
      file.puts(end_token)
    end
  end
end