Module: JsonbAccessor::Helpers

Defined in:
lib/jsonb_accessor/helpers.rb

Class Method Summary collapse

Class Method Details

.active_record_default_timezoneObject



7
8
9
# File 'lib/jsonb_accessor/helpers.rb', line 7

def active_record_default_timezone
  ActiveRecord.try(:default_timezone) || ActiveRecord::Base.default_timezone
end

.convert_keys_to_store_keys(attributes, store_key_mapping) ⇒ Object

Replaces all keys in ‘attributes` that have a defined store_key with the store_key



12
13
14
15
16
# File 'lib/jsonb_accessor/helpers.rb', line 12

def convert_keys_to_store_keys(attributes, store_key_mapping)
  attributes.stringify_keys.transform_keys do |key|
    store_key_mapping[key] || key
  end
end

.convert_store_keys_to_keys(attributes, store_key_mapping) ⇒ Object

Replaces all keys in ‘attributes` that have a defined store_key with the named key (alias)



19
20
21
# File 'lib/jsonb_accessor/helpers.rb', line 19

def convert_store_keys_to_keys(attributes, store_key_mapping)
  convert_keys_to_store_keys(attributes, store_key_mapping.invert)
end

.deserialize_value(value, attribute_type) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/jsonb_accessor/helpers.rb', line 23

def deserialize_value(value, attribute_type)
  return value if value.blank?

  if attribute_type == :datetime
    value = if value.is_a?(Array)
              value.map { |v| parse_date(v) }
            else
              parse_date(value)
            end
  end

  value
end

.parse_date(datetime) ⇒ Object

Parse datetime based on the configured default_timezone



38
39
40
41
42
43
44
# File 'lib/jsonb_accessor/helpers.rb', line 38

def parse_date(datetime)
  if active_record_default_timezone == :utc
    Time.find_zone("UTC").parse(datetime).in_time_zone
  else
    Time.zone.parse(datetime)
  end
end