Class: Ppl::Adapter::Storage::Disk

Inherits:
Ppl::Adapter::Storage show all
Defined in:
lib/ppl/adapter/storage/disk.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Ppl::Adapter::Storage

#require_contact

Constructor Details

#initialize(directory) ⇒ Disk

Returns a new instance of Disk.



23
24
25
# File 'lib/ppl/adapter/storage/disk.rb', line 23

def initialize(directory)
  @directory = directory
end

Instance Attribute Details

#directoryObject

Returns the value of attribute directory.



6
7
8
# File 'lib/ppl/adapter/storage/disk.rb', line 6

def directory
  @directory
end

#vcard_adapterObject

Returns the value of attribute vcard_adapter.



7
8
9
# File 'lib/ppl/adapter/storage/disk.rb', line 7

def vcard_adapter
  @vcard_adapter
end

Class Method Details

.create_address_book(path) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/ppl/adapter/storage/disk.rb', line 9

def self.create_address_book(path)
  if !Dir.exists? path
    FileUtils.mkdir_p(path)
  end
  storage = self.new(Dir.new(path))

  dot_ppl = File.join(path, ".ppl")
  config  = File.join(dot_ppl, "config")
  FileUtils.mkdir_p(dot_ppl)
  FileUtils.touch(config)

  storage
end

Instance Method Details

#delete_contact(contact) ⇒ Object



64
65
66
# File 'lib/ppl/adapter/storage/disk.rb', line 64

def delete_contact(contact)
  File.unlink filename_for_contact(contact)
end

#filename_for_contact(contact) ⇒ Object



68
69
70
# File 'lib/ppl/adapter/storage/disk.rb', line 68

def filename_for_contact(contact)
  filename_for_contact_id(contact.id)
end

#filename_for_contact_id(id) ⇒ Object



72
73
74
# File 'lib/ppl/adapter/storage/disk.rb', line 72

def filename_for_contact_id(id)
  File.join(@directory.path, id + ".vcf")
end

#load_address_bookObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/ppl/adapter/storage/disk.rb', line 27

def load_address_book
  address_book = Ppl::Entity::AddressBook.new

  pattern   = File.join @directory.path, "*.vcf"
  filenames = Dir.glob pattern

  filenames.each do |filename|
    contact_id = File.basename(filename).slice(0..-5)
    contact    = load_contact(contact_id)
    address_book.add_contact(contact)
  end

  return address_book
end

#load_contact(id) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/ppl/adapter/storage/disk.rb', line 42

def load_contact(id)
  filename = filename_for_contact_id(id)
  contact  = nil
  if File.exists?(filename)
    vcard   = File.read filename
    contact = @vcard_adapter.decode(vcard)
    if !contact.nil? && contact.is_a?(Ppl::Entity::Contact)
      contact.id = id
    end
  end
  return contact
end

#save_contact(contact) ⇒ Object



55
56
57
58
59
60
61
62
# File 'lib/ppl/adapter/storage/disk.rb', line 55

def save_contact(contact)
  vcard = @vcard_adapter.encode(contact)

  filename = filename_for_contact(contact)
  File.open(filename, "w") do |file|
    file.write(vcard)
  end
end