Class: Hash
Direct Known Subclasses
Class Method Summary collapse
-
.from_java_properties(string) ⇒ Object
:call-seq: Hash.from_java_properties(string).
Instance Method Summary collapse
-
#except(*keys) ⇒ Object
:call-seq: except(keys*) => hash.
-
#only(*keys) ⇒ Object
:call-seq: only(keys*) => hash.
-
#to_java_properties ⇒ Object
:call-seq: to_java_properties => string.
Class Method Details
.from_java_properties(string) ⇒ Object
:call-seq:
Hash.from_java_properties(string)
Returns a hash from a string in the Java properties file format. For example:
str = 'foo=bar\nbaz=fab'
Hash.from_properties(str)
=> { 'foo'=>'bar', 'baz'=>'fab' }.to_properties
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 |
# File 'lib/buildr/core/util.rb', line 251 def from_java_properties(string) hash = {} input_stream = Java.java.io.StringBufferInputStream.new(string) java_properties = Java.java.util.Properties.new java_properties.load input_stream keys = java_properties.keySet.iterator while keys.hasNext # Calling key.next in JRuby returns a java.lang.String, behaving as a Ruby string and life is good. # MRI, unfortunately, treats next() like the interface says returning an object that's not a String, # and the Hash doesn't work the way we need it to. Unfortunately, we can call toString on MRI's object, # but not on the JRuby one; calling to_s on the JRuby object returns what we need, but ... you guessed it. # So this seems like the one hack to unite them both. #key = Java.java.lang.String.valueOf(keys.next.to_s) key = keys.next key = key.toString unless String === key hash[key] = java_properties.getProperty(key) end hash end |
Instance Method Details
#except(*keys) ⇒ Object
:call-seq:
except(keys*) => hash
Returns a new hash without the specified keys.
For example:
{ :a=>1, :b=>2, :c=>3, :d=>4 }.except(:a, :c)
=> { :b=>2, :d=>4 }
294 295 296 |
# File 'lib/buildr/core/util.rb', line 294 def except(*keys) (self.keys - keys).inject({}) { |hash, key| hash.merge(key=>self[key]) } end |
#only(*keys) ⇒ Object
:call-seq:
only(keys*) => hash
Returns a new hash with only the specified keys.
For example:
{ :a=>1, :b=>2, :c=>3, :d=>4 }.only(:a, :c)
=> { :a=>1, :c=>3 }
281 282 283 |
# File 'lib/buildr/core/util.rb', line 281 def only(*keys) keys.inject({}) { |hash, key| has_key?(key) ? hash.merge(key=>self[key]) : hash } end |
#to_java_properties ⇒ Object
:call-seq:
to_java_properties => string
Convert hash to string format used for Java properties file. For example:
{ 'foo'=>'bar', 'baz'=>'fab' }.to_properties
=> foo=bar
baz=fab
305 306 307 308 309 310 |
# File 'lib/buildr/core/util.rb', line 305 def to_java_properties keys.sort.map { |key| value = self[key].gsub(/[\t\r\n\f\\]/) { |escape| "\\" + {"\t"=>"t", "\r"=>"r", "\n"=>"n", "\f"=>"f", "\\"=>"\\"}[escape] } "#{key}=#{value}" }.join("\n") end |