Guest User

Untitled

a guest
Feb 20th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.18 KB | None | 0 0
  1. module ActiveSupport #:nodoc:
  2. module CoreExtensions #:nodoc:
  3. module Hash #:nodoc:
  4. module Conversions
  5. module ClassMethods
  6. def typecast_xml_value(value)
  7. case value.class.to_s
  8. when 'Hash'
  9. if value['type'] == 'array'
  10. # If it has more than 2 keys tag has attributes
  11. if value.keys.size != 2
  12. value.delete('type')
  13. typecast_xml_value(value)
  14. else
  15. child_key, entries = value.detect { |k,v| k != 'type' } # child_key is throwaway
  16. if entries.nil? || (c = value['__content__'] && c.blank?)
  17. []
  18. else
  19. case entries.class.to_s # something weird with classes not matching here. maybe singleton methods breaking is_a?
  20. when "Array"
  21. entries.collect { |v| typecast_xml_value(v) }
  22. when "Hash"
  23. [typecast_xml_value(entries)]
  24. else
  25. raise "can't typecast #{entries.inspect}"
  26. end
  27. end
  28. end
  29. elsif value.has_key?("__content__")
  30. content = value["__content__"]
  31. if parser = XML_PARSING[value["type"]]
  32. if parser.arity == 2
  33. XML_PARSING[value["type"]].call(content, value)
  34. else
  35. XML_PARSING[value["type"]].call(content)
  36. end
  37. else
  38. content
  39. end
  40. elsif value['type'] == 'string' && value['nil'] != 'true'
  41. ""
  42. # blank or nil parsed values are represented by nil
  43. elsif value.blank? || value['nil'] == 'true'
  44. nil
  45. # If the type is the only element which makes it then
  46. # this still makes the value nil, except if type is
  47. # a XML node(where type['value'] is a Hash)
  48. elsif value['type'] && value.size == 1 && !value['type'].is_a?(::Hash)
  49. nil
  50. else
  51. xml_value = value.inject({}) do |h,(k,v)|
  52. h[k] = typecast_xml_value(v)
  53. h
  54. end
  55.  
  56. # Turn { :files => { :file => #<StringIO> } into { :files => #<StringIO> } so it is compatible with
  57. # how multipart uploaded files from HTML appear
  58. xml_value["file"].is_a?(StringIO) ? xml_value["file"] : xml_value
  59. end
  60. when 'Array'
  61. value.map! { |i| typecast_xml_value(i) }
  62. case value.length
  63. when 0 then nil
  64. when 1 then value.first
  65. else value
  66. end
  67. when 'String'
  68. value
  69. else
  70. raise "can't typecast #{value.class.name} - #{value.inspect}"
  71. end
  72. end
  73. end
  74. end
  75. end
  76. end
  77. end
Add Comment
Please, Sign In to add comment