Class: AppCfg::JavaProperties

Inherits:
Object
  • Object
show all
Defined in:
lib/appcfg/sources/properties_source.rb

Overview

JavaProperties class from github.com/axic/rsnippets/blob/master/javaproperties.rb (originally from devender.wordpress.com/2006/05/01/reading-and-writing-java-property-files-with-ruby/)

Consider splitting into own project and including as a gem. Some features missing: escape handling error handling, perhaps whitespace edge cases as well.

Consider checking for presence of JRuby and invoking java.util.Properties if available.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename) ⇒ JavaProperties

Returns a new instance of JavaProperties.



29
30
31
32
33
34
35
36
# File 'lib/appcfg/sources/properties_source.rb', line 29

def initialize(filename)
  @filename = filename
  @properties = {}

  IO.foreach(@filename) do |line|
    @properties[$1.strip] = $2 if line = ~ /([^=]*)=(.*)\/\/(.*)/ || line =~ /([^=]*)=(.*)/
  end
end

Instance Attribute Details

#filenameObject

Returns the value of attribute filename.



27
28
29
# File 'lib/appcfg/sources/properties_source.rb', line 27

def filename
  @filename
end

#propertiesObject

Returns the value of attribute properties.



27
28
29
# File 'lib/appcfg/sources/properties_source.rb', line 27

def properties
  @properties
end

Instance Method Details

#add(key, value = nil) ⇒ Object



44
45
46
47
# File 'lib/appcfg/sources/properties_source.rb', line 44

def add(key, value = nil)
  return unless key.length > 0
  @properties[key] = value
end

#remove(key) ⇒ Object



49
50
51
52
# File 'lib/appcfg/sources/properties_source.rb', line 49

def remove(key)
  return unless key.length > 0
  @properties.delete(key)
end

#saveObject



54
55
56
57
58
# File 'lib/appcfg/sources/properties_source.rb', line 54

def save
  file = File.new(@filename, "w+")
  @properties.each { |key, value| file.puts "#{key}=#{value}\n" }
  file.close
end

#to_sObject



38
39
40
41
42
# File 'lib/appcfg/sources/properties_source.rb', line 38

def to_s
  output = "File name #{@file}\n"
  @properties.each { |key, value| output += " #{key} = #{value}\n" }
  output
end