Class: AddressbookTxt

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename = 'addressbook.txt', path: '.') ⇒ AddressbookTxt

Returns a new instance of AddressbookTxt.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/addressbook_txt.rb', line 26

def initialize(filename='addressbook.txt', path: '.')
  
  @filename, @path = filename, path
  
  fpath = File.join(path, filename)
  
  if File.exists?(fpath) then

    @dx = import_to_dx(File.read(fpath))    
        
  else
    @dx = new_dx    
  end
end

Instance Attribute Details

#to_sObject (readonly)

Returns the value of attribute to_s.



24
25
26
# File 'lib/addressbook_txt.rb', line 24

def to_s
  @to_s
end

Instance Method Details

#dxObject



41
42
43
# File 'lib/addressbook_txt.rb', line 41

def dx()
  @dx
end

#save(filename = @filename) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/addressbook_txt.rb', line 45

def save(filename=@filename)

  s = File.basename(filename) + "\n" + dx_to_s(@dx).lines[1..-1].join
  File.write File.join(@path, filename), s
  
  xml_file = File.join(@path, filename.sub(/\.txt$/,'.xml'))
  
  if File.exists? xml_file then
    xml_buffer = File.read xml_file
    doc = RexleDiff.new(xml_buffer, @dx.to_xml, fuzzy_match: true).to_doc
    
    File.write xml_file, doc.xml(pretty: true)
  else
    File.write xml_file, @dx.to_xml(pretty: true)
  end
  
  # write the file to the archive
  archive_file = File.join(@path,'archive','addressbook-' + \
                           Date.today.year.to_s + '.xml')
  FileUtils.mkdir_p File.dirname(archive_file)
  FileUtils.cp xml_file, archive_file
      
end

#search(keyword) ⇒ Object



69
70
71
# File 'lib/addressbook_txt.rb', line 69

def search(keyword)
  dx.all.select {|r| r.x =~ /#{keyword}/i}
end