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.



158
159
160
161
162
163
164
165
# File 'lib/user_config.rb', line 158

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.



153
154
155
# File 'lib/user_config.rb', line 153

def path
  @path
end

Instance Method Details

#[](key) ⇒ Object



190
191
192
# File 'lib/user_config.rb', line 190

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

#[]=(key, val) ⇒ Object



194
195
196
# File 'lib/user_config.rb', line 194

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

#saveObject

Save cached values to the path of file.



181
182
183
184
185
186
187
188
# File 'lib/user_config.rb', line 181

def save
  unless File.exist?((dir = File.dirname(path)))
    FileUtils.mkdir_p(dir)
  end
  Kernel.open(path, 'w') do |f|
    YAML.dump(@cache, f)
  end
end

#to_yamlObject



176
177
178
# File 'lib/user_config.rb', line 176

def to_yaml
  YAML.dump(@cache)
end