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
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 |
# File 'lib/buildr/core/util.rb', line 230 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) 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 }
271 272 273 |
# File 'lib/buildr/core/util.rb', line 271 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 }
258 259 260 |
# File 'lib/buildr/core/util.rb', line 258 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
282 283 284 285 286 287 |
# File 'lib/buildr/core/util.rb', line 282 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 |