Class: JavaProperties::Properties

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/java_properties.rb

Overview

A class that can read and write to Java properties files that behaves otherwise as a standard ruby Enumerable. The keys to this object can be provided as Strings or Symbols, but internally they are Symbols.

require 'rubygems'
require 'java_properties'

# Create a new object from a file
props = JavaProperties::Properties.new("/path/to/file.properties")

# Merge in another file
props.load("/path/to/other/file.properties")

# Behaves as an Enumerable
props.each{ |key,value| puts "#{key} = #{value}" }

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ Properties

Returns a new instance of Properties.



47
48
49
50
# File 'lib/java_properties.rb', line 47

def initialize file
  @props = {}
  load(file)
end

Class Method Details

.load(file) ⇒ Object

Creates a new Properties object based on the contents of a Java properties file.



36
37
38
# File 'lib/java_properties.rb', line 36

def self.load file
  Properties.new file
end

Instance Method Details

#[](key) ⇒ Object



67
68
69
# File 'lib/java_properties.rb', line 67

def[](key)
  @props[key.to_sym]
end

#[]=(key, value) ⇒ Object



71
72
73
# File 'lib/java_properties.rb', line 71

def[]=(key,value)
  @props[key.to_sym] = value
end

#append(file, seperator = nil) ⇒ Object

Appends the current properties to the end of another properties file. Optionally, a seperator comment can be provided.



63
64
65
# File 'lib/java_properties.rb', line 63

def append file, seperator = nil
  PropFile.append(file, self, seperator)
end

#each(&block) ⇒ Object



75
76
77
# File 'lib/java_properties.rb', line 75

def each &block
  @props.each &block
end

#keysObject



79
80
81
# File 'lib/java_properties.rb', line 79

def keys
  @props.keys
end

#load(file) ⇒ Object

Merges the contents of a Java properties file with the properties already contained in this object.



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

def load file
  @props.merge! Parser.parse( PropFile.read( file ) )
end

#store(file, header = nil) ⇒ Object

Stores the current properties into a properties file. Optionally, a header comment can be provided.



55
56
57
# File 'lib/java_properties.rb', line 55

def store file, header = nil
  PropFile.write(file, self, header)
end

#to_sObject

Converts the properties contained in this object into a string that can be saved directly as a Java properties file.



87
88
89
90
91
92
93
94
95
96
# File 'lib/java_properties.rb', line 87

def to_s
  string = ""
  # Sort to make testing easier -> output will consistent
  @props.sort_by do |key,val|
    key.to_s
  end.each do |key,val|
	string << Encoding.encode(key.to_s) << "=" << Encoding.encode(val) << "\n"
  end
  string
end