Class: Diary::Store

Inherits:
Object
  • Object
show all
Defined in:
lib/diary-ruby/store.rb

Direct Known Subclasses

SecureStore

Instance Method Summary collapse

Constructor Details

#initialize(fname = nil) ⇒ Store

Returns a new instance of Store.



9
10
11
12
13
14
# File 'lib/diary-ruby/store.rb', line 9

def initialize(fname=nil)
  fname ||= DEFAULT_FILENAME

  @path = fname
  @file = PStore.new(fname)
end

Instance Method Details

#[](key) ⇒ Object



55
56
57
# File 'lib/diary-ruby/store.rb', line 55

def [](key)
  read(key)
end

#pathObject



16
17
18
# File 'lib/diary-ruby/store.rb', line 16

def path
  @path
end

#read(key) ⇒ Object



59
60
61
62
63
64
65
# File 'lib/diary-ruby/store.rb', line 59

def read(key)
  out = nil
  @file.transaction(true) do |db|
    out = db[key]
  end
  out
end

#update_db_timestamp(db) ⇒ Object



51
52
53
# File 'lib/diary-ruby/store.rb', line 51

def update_db_timestamp(db)
  db[:last_update_at] = Time.now.utc.strftime('%c')
end

#writeObject



44
45
46
47
48
49
# File 'lib/diary-ruby/store.rb', line 44

def write
  @file.transaction do |db|
    yield db
    update_db_timestamp(db)
  end
end

#write_entry(entry) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/diary-ruby/store.rb', line 20

def write_entry(entry)
  Diary.debug("WRITING ENTRY #{ entry.to_hash }")

  @file.transaction do |db|
    # entries index
    db[:entries] ||= []
    db[:entries] << entry.key unless db[:entries].include?(entry.key)

    # actual entry
    db[entry.key] = entry.to_hash.merge(
      updated_at: Time.now.utc.strftime('%c')
    )

    # reverse tags index (from tag to entries)
    db[:tags] ||= {}
    (entry.tags || []).each do |tag|
      db[:tags][tag] ||= []
      db[:tags][tag] = (db[:tags][tag] + [entry.key]).uniq
    end

    update_db_timestamp(db)
  end
end