Module: Istox::CommonHelper

Defined in:
lib/istox/helpers/common_helper.rb

Class Method Summary collapse

Class Method Details

.deep_to_h(obj) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/istox/helpers/common_helper.rb', line 29

def self.deep_to_h(obj)
  if obj.is_a?(Array)
    obj.map { |r| deep_to_h(r) }
  elsif obj.is_a?(OpenStruct) || obj.is_a?(Hash) || (obj.methods.include?(:to_h) && obj.present?)
    obj.to_h.transform_values do |v|
      if v.is_a?(OpenStruct) || v.is_a?(Array)
        deep_to_h(v)
      else
        v
      end
    end
  else
    obj
  end
end

.to_open_struct(model) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
# File 'lib/istox/helpers/common_helper.rb', line 3

def self.to_open_struct(model)
  return nil if model.blank?

  if model.is_a?(Array)
    model.map do |item|
      hash = deep_to_h(item).deep_transform_keys { |key| key.to_s.underscore.to_sym }
      to_recursive_ostruct(hash)
    end
  else
    hash = deep_to_h(model).deep_transform_keys { |key| key.to_s.underscore.to_sym }
    to_recursive_ostruct(hash)
  end
end

.to_recursive_ostruct(obj) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/istox/helpers/common_helper.rb', line 17

def self.to_recursive_ostruct(obj)
  if obj.is_a?(Hash)
    ::Istox::MyOpenStruct.new(obj.map { |key, val| [key, to_recursive_ostruct(val)] }.to_h)
  elsif obj.is_a?(Array)
    obj.map { |o| to_recursive_ostruct(o) }
  elsif obj.is_a?(OpenStruct)
    ::Istox::MyOpenStruct.new(obj)
  else # Assumed to be a primitive value
    obj
  end
end