Class: UserConfig

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

Defined Under Namespace

Classes: YAMLFile

Constant Summary collapse

@@default_value =
{}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(directory_name, opts = {}) ⇒ UserConfig

directory_name is a name of a configuration directory. opts is root directory, of which default value is ENV. opts is a file permission of the configuration directory, of which default value is 0700.



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

def initialize(directory_name, opts = {})
  @directory = File.expand_path(File.join(opts[:root] || ENV['HOME'], directory_name))
  @file = {}
  unless File.exist?(@directory)
    FileUtils.mkdir_p(@directory)
    FileUtils.chmod(opts[:permission] || 0700, @directory)
  end
end

Instance Attribute Details

#directoryObject (readonly)

Returns the value of attribute directory.



11
12
13
# File 'lib/user_config.rb', line 11

def directory
  @directory
end

Class Method Details

.default(path, default_hash) ⇒ Object



7
8
9
# File 'lib/user_config.rb', line 7

def self.default(path, default_hash)
  @@default_value[path] = default_hash
end

Instance Method Details

#all_file_pathsObject

Return an array of paths of all files.



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

def all_file_paths
  @file.map do |ary|
    file_path(ary[0])
  end
end

#create(path, value = nil) ⇒ Object

Save the configuration file of path. If we set a hash to value then its value is saved to the new configuration file.



42
43
44
45
# File 'lib/user_config.rb', line 42

def create(path, value = nil)
  yaml_file = load_file(path, true, value)
  yaml_file.save
end

#file_path(path) ⇒ Object



26
27
28
# File 'lib/user_config.rb', line 26

def file_path(path)
  File.join(@directory, path)
end

#load(path) ⇒ Object Also known as: []

Load the configuration file of path.



59
60
61
# File 'lib/user_config.rb', line 59

def load(path)
  @file[path] || load_file(path)
end

#make_directory(path, opts = {}) ⇒ Object

Make directory under the configuration directory.



48
49
50
51
52
53
54
55
56
# File 'lib/user_config.rb', line 48

def make_directory(path, opts = {})
  fpath = file_path(path)
  unless File.exist?(fpath)
    FileUtils.mkdir_p(fpath)
  end
  if opts[:mode]
    FileUtils.chmod(fpath, opts[:mode])
  end
end

#save_allObject

Save all configuration files that have already loaded.



73
74
75
76
77
# File 'lib/user_config.rb', line 73

def save_all
  @file.each_value do |yaml_file|
    yaml_file.save
  end
end