Last active
August 29, 2015 14:13
-
-
Save darinwilson/26c8b573a65d8bc4c64b to your computer and use it in GitHub Desktop.
RubyMotion for Android utility that converts a java.util.HashMap instance to a Ruby hash
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Utility class that converts a java.util.HashMap instance to a Ruby Hash. RubyMotion will | |
# start supporting this out of the box at some point, but until then, this can be used | |
# as a workaround: http://hipbyte.myjetbrains.com/youtrack/issue/RM-725 | |
# | |
# Usage: | |
# HashMapToHash.convert(hashmap) | |
# | |
# This supports nested hashes and should assure that all Java-based values are properly converted | |
# to their Ruby counterparts (i.e. java.lang.String => String). | |
# | |
# This has not been extensively tested, or optimized for performance. It should work well enough | |
# for simple cases, but may well fall over with a large HashMap. | |
# | |
class HashMapToHash | |
def self.convert(java_hashmap) | |
HashMapToHash.new.to_hash(java_hashmap) | |
end | |
def to_hash(hm) | |
return nil if hm.nil? | |
Hash.new.tap do |h| | |
it = hm.entrySet().iterator(); | |
while it.hasNext() do | |
entry = it.next() | |
h[entry.getKey()] = convert_value(entry.getValue()) | |
it.remove() | |
end | |
end | |
end | |
private | |
def convert_value(value) | |
new_value ||= to_hash(value) if hashmap?(value) | |
new_value ||= to_array(value) if array?(value) | |
new_value ||= to_boolean(value) if boolean?(value) | |
new_value ||= nil if null?(value) | |
new_value ||= value.to_s if java_string?(value) | |
new_value ||= value | |
end | |
def hashmap?(value) | |
value.class.to_s.end_with?("HashMap") | |
end | |
def array?(value) | |
value.is_a?(Array) | |
end | |
def boolean?(value) | |
["true","false"].include?(value.to_s.downcase) | |
end | |
def null?(value) | |
value.nil? || value.to_s.downcase == "null" | |
end | |
def java_string?(value) | |
value.class.to_s == "java.lang.String" | |
end | |
def to_array(array) | |
# currently, Java arrays are correctly converted to Array objects - we just need to make | |
# sure that the values are correctly converted | |
array.map { |value| convert_value(value) } | |
end | |
def to_boolean(value) | |
value.to_s.downcase == "true" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment