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
# File 'lib/drawer.rb', line 20

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

  at_exit do
    save(file)
  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



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

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)


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

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

.open!(file) ⇒ Object



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

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

.remove(file) ⇒ Object



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

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

Instance Method Details

#add(k, v) ⇒ Object



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

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

#flush_allObject



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

def flush_all
  cache.clear
end

#get(k) ⇒ Object



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

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

#get_multi(*ks) ⇒ Object



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

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

#inspectObject



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

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

#remove(k) ⇒ Object



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

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

#save(file) ⇒ Object



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

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

#set(k, v) ⇒ Object



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

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