Module: Inventory

Defined in:
lib/inventory.rb

Overview

Narou.rbのシステムが記録するデータ単位

.narou ディレクトリにYAMLファイルとして保存される scope に :global を指定するとユーザーディレクトリ/.narousetting に保存される

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.clearObject



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

def self.clear
  @@cache = {}
end

.load(name, scope = :local) ⇒ Object



17
18
19
20
21
22
23
24
25
# File 'lib/inventory.rb', line 17

def self.load(name, scope = :local)
  @@cache ||= {}
  return @@cache[name] if @@cache[name]
  {}.tap { |h|
    h.extend(Inventory)
    h.init(name, scope)
    @@cache[name] = h
  }
end

Instance Method Details

#group(group_name) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
# File 'lib/inventory.rb', line 73

def group(group_name)
  result = {}
  each do |name, value|
    next unless name =~ /^#{group_name}\.(.+)$/
    child_name = $1
    result[child_name] = value
    lodashed_name = child_name.tr("-", "_")
    result[lodashed_name] = value if child_name != lodashed_name
  end
  OpenStruct.new(result)
end

#init(name, scope) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/inventory.rb', line 31

def init(name, scope)
  dir = case scope
        when :local
          Narou.local_setting_dir
        when :global
          Narou.global_setting_dir
        else
          raise "Unknown scope"
        end
  return nil unless dir
  @mutex = Mutex.new
  @inventory_file_path = File.join(dir, name + ".yaml")
  return unless File.exist?(@inventory_file_path)
  self.merge!(Helper::CacheLoader.memo(@inventory_file_path) { |yaml|
    begin
      YAML.load(yaml)
    rescue Psych::SyntaxError
      unless restore(@inventory_file_path)
        error "#{@inventory_file_path} が壊れてるっぽい"
        raise
      end
      YAML.load_file(@inventory_file_path)
    end
  })
end

#restore(path) ⇒ Object



66
67
68
69
70
71
# File 'lib/inventory.rb', line 66

def restore(path)
  backup_path = "#{path}.backup"
  return nil unless File.exist?(backup_path)
  FileUtils.copy(backup_path, path)
  true
end

#saveObject



57
58
59
60
61
62
63
64
# File 'lib/inventory.rb', line 57

def save
  unless @inventory_file_path
    raise "not initialized setting dir yet"
  end
  @mutex.synchronize do
    File.write(@inventory_file_path, YAML.dump(self))
  end
end