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.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/nexus/config_file.rb', line 10

def initialize( configfile )
  raise 'no file given' unless configfile
  
  @all = {}
  if configfile.is_a?( String )
    @file = configfile
    
    if File.exists?( 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.



28
29
30
# File 'lib/nexus/config_file.rb', line 28

def all
  @all
end

#fileObject (readonly)

Returns the value of attribute file.



28
29
30
# File 'lib/nexus/config_file.rb', line 28

def file
  @file
end

Instance Method Details

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



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

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

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



46
47
48
49
50
51
52
# File 'lib/nexus/config_file.rb', line 46

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

#data(repo) ⇒ Object



30
31
32
33
34
35
36
# File 'lib/nexus/config_file.rb', line 30

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

#delete(*keys) ⇒ Object



70
71
72
73
74
75
# File 'lib/nexus/config_file.rb', line 70

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)


38
39
40
# File 'lib/nexus/config_file.rb', line 38

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

#merge!(other) ⇒ Object



82
83
84
85
# File 'lib/nexus/config_file.rb', line 82

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

#reposObject



54
55
56
57
58
# File 'lib/nexus/config_file.rb', line 54

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

#section(key) ⇒ Object



60
61
62
63
64
65
66
67
68
# File 'lib/nexus/config_file.rb', line 60

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



100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/nexus/config_file.rb', line 100

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