Is there a class that is equivalent to Properties in Java

O

Olivia Dou

Is there a class in the ruby lib that is equivalent to Properties class
in Java?
 
D

Devin Mullins

Olivia said:
Is there a class in the ruby lib that is equivalent to Properties class
in Java?
If you can read something that can parse and emit Java .properties
files, then no, not in standard ruby, and a quick google doesn't find much.

You can hack something together...
IO.readlines('some.properties').reject{|l|l=~/^\s*#/}.
map{|l|l.split('=',2)}
But I'm sure that misses a whole buncha edge cases, like backslash
escaping, and Ant-style property substitution.

If you mean some way to parse/emit key/value parse from/to a
human-readable format... Hash and YAML.

Devin
 
J

James Edward Gray II

Is there a class in the ruby lib that is equivalent to Properties
class
in Java?

I think the following code should cover most of the Properties class
features:

#!/usr/bin/env ruby -w

require "forwardable"
require "yaml"

class Properties
def self.load(file_path)
File.open(file_path) { |file| YAML.load(file) }
end

def initialize
@properties = Hash.new
@defaults = nil
end

attr_accessor :defaults

extend Forwardable
def_delegator :mad:properties, :[]=

def [](property)
if @defaults and not @properties.include? property
@defaults[property]
else
@properties[property]
end
end

def save(file_path)
File.open(file_path, "w") { |file| YAML.dump(self, file) }
end
end

__END__

Hope that helps.

James Edward Gray II
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top