Class: Moltrio::Config::FileStorage

Inherits:
Storage
  • Object
show all
Defined in:
lib/moltrio/config/storage/file_storage.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ FileStorage

Returns a new instance of FileStorage.



16
17
18
# File 'lib/moltrio/config/storage/file_storage.rb', line 16

def initialize(path)
  @path = path
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



14
15
16
# File 'lib/moltrio/config/storage/file_storage.rb', line 14

def path
  @path
end

Instance Method Details

#[](key) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/moltrio/config/storage/file_storage.rb', line 20

def [](key)
  if has_key?(key)
    *path, leaf = splitted_key(key)
    hamster_to_ruby(traverse(path).fetch(leaf))
  else
    nil
  end
end

#[]=(dotted_key, value) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/moltrio/config/storage/file_storage.rb', line 29

def []=(dotted_key, value)
  ancestor_keys = splitted_key(dotted_key)
  current_value = value
  base_hash = hash

  while ancestor_keys.any?
    *ancestor_keys, current_key = ancestor_keys

    old_value = traverse(ancestor_keys, base_hash: base_hash)
    current_value = old_value.put(current_key, current_value)
  end

  unless @hash.equal?(base_hash)
    # Retry the change. The hash was updated by other thread while we
    # were computing the new hash.
    return self[dotted_key] = value
  end

  @hash = current_value

  save
end

#has_key?(key) ⇒ Boolean

Returns:

  • (Boolean)


52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/moltrio/config/storage/file_storage.rb', line 52

def has_key?(key)
  not_found = Object.new
  value = splitted_key(key).inject(hash) do |current, part|
    if current.respond_to?(:has_key?) && current.has_key?(part)
      current[part]
    else
      break not_found
    end
  end

  !value.equal?(not_found)
end

#on_namespace(namespace) ⇒ Object



65
66
67
# File 'lib/moltrio/config/storage/file_storage.rb', line 65

def on_namespace(namespace)
  scoped(namespace)
end