Module: Istox::CommonHelper
- Defined in:
- lib/istox/helpers/common_helper.rb
Class Method Summary collapse
- .deep_to_h(obj) ⇒ Object
- .to_boolean(input) ⇒ Object
- .to_datetime(input) ⇒ Object
- .to_open_struct(model) ⇒ Object
- .to_recursive_ostruct(obj) ⇒ Object
Class Method Details
.deep_to_h(obj) ⇒ Object
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/istox/helpers/common_helper.rb', line 46 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_boolean(input) ⇒ Object
16 17 18 |
# File 'lib/istox/helpers/common_helper.rb', line 16 def self.to_boolean(input) !(input.blank? || input.to_s.downcase == 'false' || input.to_s.downcase == '0') end |
.to_datetime(input) ⇒ Object
3 4 5 6 7 8 9 10 11 12 13 14 |
# File 'lib/istox/helpers/common_helper.rb', line 3 def self.to_datetime(input) return nil if input.blank? begin is_numeric = true if Integer input rescue StandardError false end # is unix timestamp is_numeric ? Time.at(input.to_i).to_datetime : Time.parse(input) end |
.to_open_struct(model) ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/istox/helpers/common_helper.rb', line 20 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
34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/istox/helpers/common_helper.rb', line 34 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 |