item_attributes.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. module Import
  2. class Exchange
  3. class ItemAttributes
  4. def self.extract(resource)
  5. new(resource).extract
  6. end
  7. def initialize(resource)
  8. @resource = resource
  9. end
  10. def extract
  11. @extract ||= begin
  12. properties = @resource.get_all_properties!
  13. result = normalize(properties)
  14. flattened = flatten(result)
  15. booleanize_values(flattened)
  16. end
  17. end
  18. private
  19. def booleanize_values(properties)
  20. properties.each do |key, value|
  21. if value.is_a?(String)
  22. next if !%w[true false].include?(value)
  23. properties[key] = value == 'true'
  24. elsif value.is_a?(Hash)
  25. properties[key] = booleanize_values(value)
  26. end
  27. end
  28. end
  29. def normalize(properties)
  30. properties.each_with_object({}) do |(key, value), result|
  31. next if key == :body
  32. if value[:text]
  33. result[key] = value[:text]
  34. elsif value[:attribs]
  35. result[key] = value[:attribs]
  36. elsif value[:elems]
  37. result[key] = sub_elems(value[:elems])
  38. end
  39. end
  40. end
  41. def sub_elems(elems)
  42. elems.each_with_object({}) do |elem, result|
  43. if elem[:entry]
  44. result.merge!( sub_elem_entry( elem[:entry] ) )
  45. else
  46. result.merge!( normalize(elem) )
  47. end
  48. end
  49. end
  50. def sub_elem_entry(entry)
  51. entry_value = {}
  52. if entry[:elems]
  53. entry_value = sub_elems(entry[:elems])
  54. end
  55. if entry[:text]
  56. entry_value[:text] = entry[:text]
  57. end
  58. if entry[:attribs].present?
  59. entry_value.merge!(entry[:attribs])
  60. end
  61. entry_key = entry_value.delete(:key)
  62. {
  63. entry_key => entry_value
  64. }
  65. end
  66. def flatten(properties, prefix: nil)
  67. properties.each_with_object({}) do |(key, value), result|
  68. result_key = key
  69. if prefix
  70. result_key = if %i[text id].include?(key) && ( !result[result_key] || result[result_key] == value )
  71. prefix
  72. else
  73. "#{prefix}.#{key}".to_sym
  74. end
  75. end
  76. result_key = result_key.to_s.downcase
  77. if value.is_a?(Hash)
  78. sub_result = flatten(value, prefix: result_key)
  79. result.merge!(sub_result)
  80. else
  81. result[result_key] = value.to_s
  82. end
  83. end
  84. end
  85. end
  86. end
  87. end