Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/trials/extensions/hash.rb

Instance Method Summary collapse

Instance Method Details

#sanitize(schema, date_format: '%Y-%m-%d') ⇒ Object



41
42
43
44
45
46
47
# File 'lib/trials/extensions/hash.rb', line 41

def sanitize(schema, date_format: '%Y-%m-%d')
  cp = self.dup
  schema.each do |key, type|
    cp = cp.sanitize_value(key, type, date_format: date_format)
  end
  cp
end

#sanitize_value(key, type, date_format: nil, datetime_format: nil) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/trials/extensions/hash.rb', line 18

def sanitize_value(key, type, date_format: nil, datetime_format: nil)
  self.merge(
    key => or_nil do
      case type
      when :date
        Date.strptime(*[self.dig(key), date_format].compact)
      when :datetime
        DateTime.parse(*[self.dig(key), datetime_format].compact)
      when :integer, :int
        self.dig(key).to_i
      when :float
        self.dig(key).to_f
      when :string
        self.dig(key).to_s
      when :present?
        self.dig(key).present?
      when :blank?
        self.dig(key).blank?
      end
    end
  )
end

#to_os(n = nil) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/trials/extensions/hash.rb', line 2

def to_os(n = nil)
  n ||= self

  case n
  when Array
    n.map { |x| to_os(x) }
  when NilClass, Hash
    n
      .map { |k, v| [k, to_os(v)] }
      .to_h
      .then { |x| OpenStruct.new(x) }
  else
    n
  end
end