Module: HasHelpers::DNUtils

Defined in:
app/models/has_helpers/dn_utils.rb

Instance Method Summary collapse

Instance Method Details

#ensure_json_serializable(obj) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'app/models/has_helpers/dn_utils.rb', line 46

def ensure_json_serializable(obj)
  case obj
  when Hash
    obj.transform_keys(&:to_s).transform_values { |v| ensure_json_serializable(v) }
  when Array
    obj.map { |v| ensure_json_serializable(v) }
  when Symbol
    obj.to_s
  when Time
    obj.iso8601
  else
    obj
  end
end

#update_denormalized_columnsObject



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'app/models/has_helpers/dn_utils.rb', line 6

def update_denormalized_columns
  return unless ::Rails.application.config.x.dn_enabled == true
  dependencies = "#{self.class.table_name.camelize}Dependencies".constantize rescue nil
  return if dependencies.nil?
  type = saved_changes.key?("id") ? "insert" : "update"
  changes = saved_changes

  if dependencies.respond_to?(:indirect_fields) && type == "update"
    reloaded_resource = self.class.find_by(id: self.id)
    # indirect_field stores the fileds that are changed on a db level
    # for example the column name on advisors changes with a db trigger (not at rails level)
    dependencies.indirect_fields.each { |field| changes["#{field}"] = [self.send(field), reloaded_resource.send(field)] if self.send(field) != reloaded_resource.send(field) }
  end
  return if dependencies.dependent_tables.keys.intersection(changes.keys).empty?

  if Object.const_defined?("ChangeLog") && ::ActiveRecord::Base.connection.data_source_exists?("change_logs")
    exists_subquery = "EXISTS (
      SELECT 1
      FROM unnest(changed_columns) AS col
      WHERE col = ANY(ARRAY[?])
    )"

    change_log_id = ChangeLog.select(:id).
      where(record_id: id, type: type, denormalized_at: nil, table_name: self.class.table_name).
      where(type == "insert" ? "true" : exists_subquery, dependencies.dependent_tables.keys).
      order(id: :desc).
      first&.id
  end
  if dependencies.present? && changes.present?
    ::GoodJob::DNWorker.perform_deferred(
      self.class.table_name,
      ensure_json_serializable(dependencies.dependent_tables),
      self.class.name,
      id,
      ensure_json_serializable(changes),
      change_log_id
    )
  end
end