Class: UserConfig::YAMLFile

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, default, opts = {}) ⇒ YAMLFile

path is path of yaml file, which saves pairs of key and value. default is a hash saving default value. if opts[:merge] is true then values of an instance are merged with default values.



85
86
87
88
89
90
91
92
# File 'lib/user_config.rb', line 85

def initialize(path, default, opts = {})
  @path = path
  @default = default
  @cache = load
  if opts[:merge]
    @cache.merge!(@default)
  end
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



80
81
82
# File 'lib/user_config.rb', line 80

def path
  @path
end

Instance Method Details

#[](key) ⇒ Object



117
118
119
# File 'lib/user_config.rb', line 117

def [](key)
  @cache[key] || @default[key]
end

#[]=(key, val) ⇒ Object



121
122
123
# File 'lib/user_config.rb', line 121

def []=(key, val)
  @cache[key] = val
end

#saveObject

Save cached values to the path of file.



108
109
110
111
112
113
114
115
# File 'lib/user_config.rb', line 108

def save
  unless File.exist?((dir = File.dirname(path)))
    FileUtils.mkdir_p(dir)
  end
  open(path, 'w') do |f|
    f.print to_yaml
  end
end

#to_yamlObject



103
104
105
# File 'lib/user_config.rb', line 103

def to_yaml
  YAML.dump(@cache)
end