Class: Drawer

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, store = DrawerStore) ⇒ Drawer

Returns a new instance of Drawer.



20
21
22
23
24
25
26
27
28
# File 'lib/drawer.rb', line 20

def initialize(file, store = DrawerStore)
  @file  = file
  @store = store
  @cache = store.load(file) || {}

  at_exit do
    save
  end
end

Instance Attribute Details

#cacheObject (readonly)

Returns the value of attribute cache.



17
18
19
# File 'lib/drawer.rb', line 17

def cache
  @cache
end

#storeObject (readonly)

Returns the value of attribute store.



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

def store
  @store
end

Class Method Details

.create(file) ⇒ Object



75
76
77
78
79
80
# File 'lib/drawer.rb', line 75

def self.create(file)
  unless File.exists?(file)
    FileUtils.mkdir_p File.dirname(file)
    FileUtils.touch(file)
  end
end

.open(file) {|drawer| ... } ⇒ Object

Yields:

  • (drawer)


62
63
64
65
66
67
# File 'lib/drawer.rb', line 62

def self.open(file, &block)
  file = File.expand_path(file)
  drawer = Drawer.new(file)
  yield drawer if block_given?
  drawer
end

.open!(file) ⇒ Object



69
70
71
72
73
# File 'lib/drawer.rb', line 69

def self.open!(file)
  file = File.expand_path(file)
  create(file)
  open(file)
end

.remove(file) ⇒ Object



82
83
84
# File 'lib/drawer.rb', line 82

def self.remove(file)
  FileUtils.rm(file)
end

Instance Method Details

#add(k, v) ⇒ Object



42
43
44
# File 'lib/drawer.rb', line 42

def add(k, v)
  set(k, v) unless cache[k]
end

#flush_allObject



50
51
52
# File 'lib/drawer.rb', line 50

def flush_all
  cache.clear
end

#get(k) ⇒ Object



30
31
32
# File 'lib/drawer.rb', line 30

def get(k)
  cache[k] or (set(k, yield) if block_given?)
end

#get_multi(*ks) ⇒ Object



34
35
36
# File 'lib/drawer.rb', line 34

def get_multi(*ks)
  ks.collect { |k| get(k) }
end

#inspectObject



54
55
56
# File 'lib/drawer.rb', line 54

def inspect
  "Drawer count: #{cache.size}. Type 'cache' to view the content."
end

#remove(k) ⇒ Object



46
47
48
# File 'lib/drawer.rb', line 46

def remove(k)
  cache.delete(k)
end

#save(file = @file) ⇒ Object



58
59
60
# File 'lib/drawer.rb', line 58

def save(file=@file)
  store.save(@cache, file)
end

#set(k, v) ⇒ Object



38
39
40
# File 'lib/drawer.rb', line 38

def set(k, v)
  cache[k] = v
end