Class: CrazyDoll::Config::Backend::YAML

Inherits:
Object
  • Object
show all
Defined in:
lib/crazy_doll/config_backend/yaml.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ YAML

Returns a new instance of YAML.



9
10
11
12
# File 'lib/crazy_doll/config_backend/yaml.rb', line 9

def initialize(file)
  @file = file
  self.load
end

Instance Attribute Details

#instancesObject (readonly)

Returns the value of attribute instances.



8
9
10
# File 'lib/crazy_doll/config_backend/yaml.rb', line 8

def instances
  @instances
end

Instance Method Details

#[](key) ⇒ Object



63
64
65
# File 'lib/crazy_doll/config_backend/yaml.rb', line 63

def [](key)
  @instances[key]
end

#config_of(key) ⇒ Object



54
55
56
57
# File 'lib/crazy_doll/config_backend/yaml.rb', line 54

def config_of(key)
  key = real_key(key)
  @instances[key] ||= CrazyDoll::Config::Instance.new(key, {})
end

#create_instances(data = nil) ⇒ Object



32
33
34
35
36
37
38
39
40
# File 'lib/crazy_doll/config_backend/yaml.rb', line 32

def create_instances(data=nil)
  return false unless data.is_a?(Hash)
  @instances ||= {}
  keys = data.keys
  keys.each do |k|
    key = real_key(k)
    @instances[key] = CrazyDoll::Config::Instance.new(key, data[k])
  end
end

#end_useObject



23
24
25
# File 'lib/crazy_doll/config_backend/yaml.rb', line 23

def end_use
  @thread.kill if @thread and @thread.alive?
end

#loadObject



42
43
44
45
# File 'lib/crazy_doll/config_backend/yaml.rb', line 42

def load
  setup_table_if_needed
  create_instances(::YAML.load_file(@file))
end

#real_key(k) ⇒ Object



59
60
61
# File 'lib/crazy_doll/config_backend/yaml.rb', line 59

def real_key(k)
  [String, Symbol].include?(k.class) ? k.to_s : k.class.to_s
end

#saveObject



47
48
49
50
51
52
# File 'lib/crazy_doll/config_backend/yaml.rb', line 47

def save
  setup_table_if_needed
  d = {}
  @instances.each { |k,v| d[k] = v.config }
  File.open(@file, 'w+') { |f| f.write(::YAML.dump(d)) }
end

#setup_table_if_neededObject



27
28
29
30
# File 'lib/crazy_doll/config_backend/yaml.rb', line 27

def setup_table_if_needed
  FileUtis.mkdir_p(File.dirname(@file)) unless FileTest.directory?(File.dirname(@file))
  File.open(@file, "w+") { |f| f.write(::YAML.dump({})) } unless FileTest.file?(@file)
end

#start_useObject



14
15
16
17
18
19
20
21
# File 'lib/crazy_doll/config_backend/yaml.rb', line 14

def start_use
  @thread = Thread.new(self) do |b|
    loop do
      sleep 60
      b.save
    end
  end
end