Class: InsightsExport::ExportModels

Inherits:
Object
  • Object
show all
Defined in:
lib/insights_export/export_models.rb

Class Method Summary collapse

Class Method Details

.config_fileObject



3
4
5
# File 'lib/insights_export/export_models.rb', line 3

def self.config_file
  InsightsExport.configuration.export_path
end

.exportObject



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
45
46
47
48
49
# File 'lib/insights_export/export_models.rb', line 15

def self.export
  input = YAML::load_file(config_file) rescue nil
  structure = get_structure.deep_stringify_keys
  output = {}

  if input.present?
    output = input.dup.deep_stringify_keys
    structure.each do |model_name, model_structure|
      # we already had this model in the output
      if output[model_name].present?
        model_structure.each do |key, value|
          if key == 'custom'
            next
          elsif key == 'columns' || key == 'aggregate'
            output[model_name][key] ||= {}
            value.each do |value_key, value_value|
              existing = output[model_name][key][value_key]
              if existing != false
                output[model_name][key][value_key] = (existing || {}).merge(value_value)
              end
            end
          elsif key != 'enabled'
            output[model_name][key] = value
          end
        end
      else
        output[model_name] = model_structure
      end
    end
  else
    output = structure
  end

  File.open(config_file, 'w') {|f| f.write output.deep_stringify_keys.to_yaml }
end

.get_structureObject



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/insights_export/export_models.rb', line 51

def self.get_structure
  Rails.application.eager_load! if Rails.env.development?

  models = ActiveRecord::Base.descendants

  # skip all abstract classes (e.g. ApplicationRecord)
  models = models.reject { |m| m.abstract_class? }

  # models to include
  only_models = InsightsExport.configuration.only_models
  if only_models.present?
    models = models.select { |m| only_models.select { |lm| lm.is_a?(Regexp) ? lm.match(m.to_s) : lm == m.to_s }.present? }
  end

  # models to exclude
  except_models = InsightsExport.configuration.except_models
  if except_models.present?
    models = models.reject { |m| except_models.select { |lm| lm.is_a?(Regexp) ? lm.match(m.to_s) : lm == m.to_s }.present? }
  end

  # sort them
  models = models.sort_by { |m| m.to_s }

  # cache the strings
  model_strings = models.map(&:to_s)

  # show that we're doing something
  puts "InsightsExport: #{model_strings.join(', ')}"

  # this will contain our result
  return_object = {}

  models.each do |model|
    columns_hash = model.columns_hash

    begin
      model_structure = {
        enabled: true,
        model: model.to_s,
        table_name: model.table_name,
        primary_key: model.primary_key,
        columns: columns_hash.map do |key, column|
          obj = if column.type.in? %i(datetime date)
                  { type: :time }
                elsif column.type.in? %i(integer decimal float)
                  { type: :number }
                elsif column.type.in? %i(string text)
                  { type: :string }
                elsif column.type.in? %i(boolean)
                  { type: :boolean }
                elsif column.type.in? %i(json)
                  { type: :payload }
                elsif column.type.in? %i(geography)
                  { type: :geo }
                else
                  puts "Warning! Unknown column type: :#{column.type} for #{model.to_s}, column #{key}"
                  { unknown: column.type }
                end

          if key == model.primary_key
            obj[:index] = :primary_key
          end

          [key.to_sym, obj]
        end.to_h,
        custom: {},
        links: {
          incoming: {},
          outgoing: {}
        }
      }

      model.reflections.each do |association_name, reflection|
        begin
          reflection_class = reflection.class_name.gsub(/^::/, '')

          next unless model_strings.include?(reflection_class)

          if reflection.macro == :belongs_to
            # reflection_class # User
            # reflection.foreign_key # user_id
            # reflection.association_primary_key # id

            model_structure[:columns].delete(reflection.foreign_key.to_sym)
            model_structure[:links][:outgoing][association_name] = {
              model: reflection_class,
              model_key: reflection.association_primary_key,
              my_key: reflection.foreign_key
            }
          elsif reflection.macro.in? %i(has_one has_many)
            # skip has_many :through associations
            if reflection.options.try(:[], :through).present?
              next
            end

            model_structure[:links][:incoming][association_name] = {
              model: reflection_class,
              model_key: reflection.foreign_key,
              my_key: reflection.association_primary_key
            }
          else
            puts "Warning! Unknown reflection :#{reflection.macro} for association '#{association_name}' on model '#{model.to_s}'"
          end
        rescue => error
          puts "!! Error when exporting association '#{association_name}' on model '#{model.to_s}'"
          print_exception(error)
        end
      end

      return_object[model.to_s] = model_structure
    rescue => error
      puts "!! Error when exporting model '#{model.to_s}'"
      print_exception(error)
    end
  end

  return_object.sort_by { |k, v| k }.to_h.deep_stringify_keys
end

.loadObject



7
8
9
10
11
12
13
# File 'lib/insights_export/export_models.rb', line 7

def self.load
  structure = YAML::load_file(config_file) rescue get_structure

  structure.select { |k, v| v['enabled'] }.map do |k, v|
    [k, v.merge({ 'columns' => v['columns'].select { |_, vv| vv.present? } })]
  end.to_h
end


170
171
172
173
174
175
176
177
# File 'lib/insights_export/export_models.rb', line 170

def self.print_exception(error)
  puts "!! Exception: #{error.message}"
  if InsightsExport.configuration.debug
    puts error.backtrace
  else
    puts "-> Set config.debug = true to see the full backtrace"
  end
end