Class: YKK

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ YKK

Returns a new instance of YKK.



20
21
22
23
# File 'lib/ykk.rb', line 20

def initialize(options = {})
  self.dir = options[:dir]
  self.partition_size = options[:partition_size] || 0
end

Instance Attribute Details

#dirObject

Returns the value of attribute dir.



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

def dir
  @dir
end

#partition_sizeObject

Returns the value of attribute partition_size.



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

def partition_size
  @partition_size
end

Class Method Details

.inspectObject



14
15
16
# File 'lib/ykk.rb', line 14

def self.inspect
  @instance.inspect
end

.method_missing(method, *args, &block) ⇒ Object



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

def self.method_missing(method, *args, &block)
  if @instance.respond_to?(method)
    @instance.__send__(method, *args, &block)
  else
    super
  end
end

Instance Method Details

#<<(value) ⇒ Object



25
26
27
28
29
# File 'lib/ykk.rb', line 25

def <<(value)
  key = key_gen(value)
  self[key] = value
  key
end

#[](key) ⇒ Object



31
32
33
34
35
# File 'lib/ykk.rb', line 31

def [](key)
  path = file_of(key)
  return nil unless File.exists?(path)
  YAML.load(File.read(path))
end

#[]=(key, value) ⇒ Object



41
42
43
44
45
46
# File 'lib/ykk.rb', line 41

def []=(key, value)
  path = file_of(key)
  dirname = File.dirname(path)
  FileUtils.mkdir_p(dirname) unless File.exists?(dirname)
  File.open(path, 'wb') { |f| f << value.to_yaml }
end

#delete(key) ⇒ Object



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

def delete(key)
  path = file_of(key)
  File.delete(path) if File.exists?(path)
  nil
end

#file_of(key) ⇒ Object

Raises:

  • (ArgumentError)


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

def file_of(key)
  key = key.to_s
  raise ArgumentError, 'invalid key' unless key =~ /^[\w\/]+$/
  raise "dir is not specified" unless dir
  File.join(dir, *partition(key))
end

#inspectObject



70
71
72
73
74
75
# File 'lib/ykk.rb', line 70

def inspect
  pairs = Dir.glob(dir + '/*').map {|f|
    "#{File.basename(f).inspect}: #{YAML.load_file(f).inspect}"
  }
  "YKK(#{pairs.join ', '})"
end

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)


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

def key?(key)
  !!self[key]
end

#key_gen(value) ⇒ Object



66
67
68
# File 'lib/ykk.rb', line 66

def key_gen(value)
  Digest::SHA1.hexdigest(value.to_yaml)
end

#partition(key) ⇒ Object



61
62
63
64
# File 'lib/ykk.rb', line 61

def partition(key)
  return [key] if /\// =~ key || self.partition_size <= 0
  key.scan(/.{1,#{partition_size}}/)
end