Class: Lightly

Inherits:
Object
  • Object
show all
Defined in:
lib/lightly/lightly.rb,
lib/lightly/version.rb

Constant Summary collapse

VERSION =
"0.2.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Lightly

Returns a new instance of Lightly.



7
8
9
10
11
12
# File 'lib/lightly/lightly.rb', line 7

def initialize(opts={})
  @dir = opts[:dir] || 'cache'
  @life = opts[:life] || 3600
  @hash = opts.key?(:hash) ? opts[:hash] : true
  @enabled = true
end

Instance Attribute Details

#dirObject

Returns the value of attribute dir.



5
6
7
# File 'lib/lightly/lightly.rb', line 5

def dir
  @dir
end

#hashObject

Returns the value of attribute hash.



5
6
7
# File 'lib/lightly/lightly.rb', line 5

def hash
  @hash
end

#lifeObject

Returns the value of attribute life.



5
6
7
# File 'lib/lightly/lightly.rb', line 5

def life
  @life
end

Instance Method Details

#cached?(key) ⇒ Boolean

Returns:

  • (Boolean)


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

def cached?(key)
  path = get_path key
  File.exist?(path) and File.size(path) > 0 and !expired?(path)
end

#clear(key) ⇒ Object



22
23
24
25
# File 'lib/lightly/lightly.rb', line 22

def clear(key)
  path = get_path key
  FileUtils.rm path if File.exist? path
end

#disableObject



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

def disable
  @enabled = false
end

#enableObject



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

def enable
  @enabled = true
end

#enabled?Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/lightly/lightly.rb', line 32

def enabled?
  @enabled
end

#flushObject



27
28
29
30
# File 'lib/lightly/lightly.rb', line 27

def flush
  return false if dir == '/' || dir.empty?
  FileUtils.rm_rf dir
end

#get(key, &block) ⇒ Object



14
15
16
17
18
19
20
# File 'lib/lightly/lightly.rb', line 14

def get(key, &block)
  return load key if cached?(key) && enabled?

  content = block.call
  save key, content if content && enabled?
  content
end

#get_path(key) ⇒ Object



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

def get_path(key)
  key = Digest::MD5.hexdigest(key) if hash
  File.join dir, key
end

#save(key, content) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/lightly/lightly.rb', line 54

def save(key, content)
  FileUtils.mkdir_p dir
  path = get_path key
  File.open path, 'wb' do |f| 
    f.write Marshal.dump content
  end
end