Class: Hash

Inherits:
Object show all
Defined in:
lib/buildr/core/util.rb

Class Method Summary collapse

Instance Method Summary collapse

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


279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
# File 'lib/buildr/core/util.rb', line 279

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 }


322
323
324
# File 'lib/buildr/core/util.rb', line 322

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 }


309
310
311
# File 'lib/buildr/core/util.rb', line 309

def only(*keys)
  keys.inject({}) { |hash, key| has_key?(key) ? hash.merge(key=>self[key]) : hash }
end

#to_java_propertiesObject

: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


333
334
335
336
337
338
# File 'lib/buildr/core/util.rb', line 333

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