Skip to content

Instantly share code, notes, and snippets.

@atheiman
Last active January 29, 2017 01:00
Show Gist options
  • Save atheiman/7b334570b6bf0b47a2bbadface0894c9 to your computer and use it in GitHub Desktop.
Save atheiman/7b334570b6bf0b47a2bbadface0894c9 to your computer and use it in GitHub Desktop.
Ruby hash to Java properties file
class Hash
def to_java_properties_hash(prefix='')
properties = {}
self.each do |property, value|
new_prefix = prefix.empty? ? property.to_s : prefix + '.' + property.to_s
if value.respond_to? :to_java_properties_hash
properties.merge!(value.to_java_properties_hash(new_prefix))
else
properties[new_prefix] = value.to_s
end
end
# return the sorted hash
Hash[ properties.sort_by { |k,v| k.to_s } ]
end
def to_java_properties_lines
lines = []
self.to_java_properties_hash.each do |k,v|
# escape '=', ':', and newline ("\n") with a backslash
lines << "#{k.gsub(/([=:\n])/, '\\\\\1')}=#{v.gsub(/([=:\n])/, '\\\\\1')}"
end
lines
end
def to_java_properties_string
self.to_java_properties_lines.join("\n")
end
end
describe Hash do
let(:properties) do
{
'a' => 'b',
'c.4' => {
:blue => 'green',
'purple' => {
11 => '14'
},
'11.12' => 'http://rundeck.url/A=B&C=D'
},
'_' => '!@#$%^&*()'
}
end
describe '#to_java_properties_hash' do
it 'returns a java properties hash' do
expect(properties.to_java_properties_hash).to eql({
"_" => "!@\#$%^&*()",
"a" => "b",
"c.4.11.12" => "http://rundeck.url/A=B&C=D",
"c.4.blue" => "green",
"c.4.purple.11" => "14"
})
end
it 'returns a hash sorted by key' do
expect({ c: 'd', a: 'b' }.to_java_properties_hash.keys).to eql(['a', 'c'])
expect({ c: 'd', a: 'b' }.to_java_properties_hash.keys).to_not eql(['c', 'a'])
end
end
describe '#to_java_properties_lines' do
it 'returns java properties file lines' do
expect(properties.to_java_properties_lines).to eql([
"_=!@\#$%^&*()",
"a=b",
"c.4.11.12=http\\://rundeck.url/A\\=B&C\\=D",
"c.4.blue=green",
"c.4.purple.11=14"
])
end
end
describe '#to_java_properties_string' do
it 'returns java properties file content' do
expect(properties.to_java_properties_string).to eql(
'_=!@#$%^&*()
a=b
c.4.11.12=http\://rundeck.url/A\=B&C\=D
c.4.blue=green
c.4.purple.11=14'
)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment