Class: Nexus::ConfigFile

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(configfile) ⇒ ConfigFile

Returns a new instance of ConfigFile.



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/nexus/config_file.rb', line 15

def initialize( configfile )
  raise 'no file given' unless configfile
  
  @all = {}
  if configfile.is_a?( String )
    @file = configfile
    
    if File.exist?( configfile )
      @all = YAML.load( ::File.read( configfile ) )
    else
      store # make sure we can write it
    end
  elsif configfile
    @file = configfile.file
    @all = configfile.all
  end
end

Instance Attribute Details

#allObject (readonly)

Returns the value of attribute all.



33
34
35
# File 'lib/nexus/config_file.rb', line 33

def all
  @all
end

#fileObject (readonly)

Returns the value of attribute file.



33
34
35
# File 'lib/nexus/config_file.rb', line 33

def file
  @file
end

Instance Method Details

#[](key, repo = nil) ⇒ Object



47
48
49
# File 'lib/nexus/config_file.rb', line 47

def []( key, repo = nil )
  data( repo )[ key ]
end

#[]=(key, repo, value) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/nexus/config_file.rb', line 51

def []=( key, repo, value )
  if value.nil?
    data( repo ).delete( key )
  else
    data( repo )[ key ] = value
  end
end

#data(repo) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/nexus/config_file.rb', line 35

def data( repo )
  if repo
    ( @all[ repo ] ||= {} )
  else
    @all
  end
end

#delete(*keys) ⇒ Object



75
76
77
78
79
80
# File 'lib/nexus/config_file.rb', line 75

def delete( *keys )
  delete_map( all, *keys )
  all.each do |k,v|
    delete_map(v, *keys ) if v.is_a? Hash
  end
end

#key?(key, repo = nil) ⇒ Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/nexus/config_file.rb', line 43

def key?( key, repo = nil )
  data( repo ).key? key
end

#merge!(other) ⇒ Object



87
88
89
90
# File 'lib/nexus/config_file.rb', line 87

def merge!( other )
  map = other.all
  merge_map( @all, map )
end

#reposObject



59
60
61
62
63
# File 'lib/nexus/config_file.rb', line 59

def repos
  all.collect do |k,v|
    k if v.is_a? Hash
  end.select { |s| s }
end

#section(key) ⇒ Object



65
66
67
68
69
70
71
72
73
# File 'lib/nexus/config_file.rb', line 65

def section( key )
  all.dup.select do |k,v|
    if v.is_a? Hash
      v.delete_if { |kk,vv| kk != key }
    else
      k == key
    end
  end
end

#storeObject



105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/nexus/config_file.rb', line 105

def store
  dirname = File.dirname( @file )
  Dir.mkdir( dirname ) unless File.exist?( dirname )
  new = !File.exist?( @file )
  
  File.open( @file, 'w') do |f|
    f.write @all.to_yaml
  end
  if new
    File.chmod( 0100600, @file ) rescue nil
  end
end