Module: Fixturing

Defined in:
lib/fixturing.rb

Class Method Summary collapse

Class Method Details

.beautify_fixture_ids(options = {}) ⇒ Object

Adds model conform fixture ids In STI, fixture name are rewritten with name of model Example: product_153 will become plant_009


293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# File 'lib/fixturing.rb', line 293

def beautify_fixture_ids(options = {})
  path = options[:path] || directory
  # Load and prepare fixtures
  data = {}
  model_ids = {}
  Ekylibre::Schema.tables.each do |table, _columns|
    records = YAML.load_file(path.join("#{table}.yml"))
    base_model = table.to_s.classify
    counter = {}
    data[table.to_s] = records.values.sort { |a, b| [a['type'] || base_model, a['id']] <=> [b['type'] || base_model, b['id']] }.inject({}) do |hash, attributes|
      model = attributes['type'] ? attributes['type'].underscore.pluralize : table.to_s
      counter[model] ||= 0
      counter[model] += 1
      hash["#{model}_#{counter[model].to_s.rjust(3, '0')}"] = attributes
      hash
    end
  end

  data.each do |table, records|
    records.each do |record, attributes|
      data[table][record] = attributes.sort { |a, b| a.first <=> b.first }.inject({}) do |hash, pair|
        hash[pair.first] = pair.second
        hash
      end
    end
  end

  # Write
  Ekylibre::Schema.tables.each do |table, _columns|
    File.open(path.join("#{table}.yml"), 'wb') do |f|
      f.write data[table].to_yaml
    end
  end
end

.columnize_keysObject

Convert reflection to hard representation in fixtures

my_thing: things_001             => my_thing_id: 1
my_polymorph: things_001 (Thing) => my_polymorph_id: 1
                                    my_polymorph_type: Thing

146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# File 'lib/fixturing.rb', line 146

def columnize_keys
  # Load and prepare fixtures
  data = {}
  Ekylibre::Schema.tables.each do |table, _columns|
    records = YAML.load_file(directory.join("#{table}.yml"))
    ids = records.values.collect { |a| a['id'] }.compact.map(&:to_i)
    records.each do |record, attributes|
      next if attributes['id']
      id = record.split('_').last.to_i
      attributes['id'] = ids.include?(id) ? (1..(ids.max + 10)).to_a.detect { |x| !ids.include?(x) } : id
      ids << attributes['id']
    end
    data[table.to_s] = records
  end

  # Convert
  Ekylibre::Schema.tables.each do |table, columns|
    columns.each do |column, definition|
      next unless references = definition[:references]
      if references.is_a?(Symbol)
        # Standard reflection case
        foreign_model = references.to_s.camelcase.constantize
        puts references.inspect.red unless data[foreign_model.table_name]
        data[table.to_s].each do |record, attributes|
          reflection = column.to_s.gsub(/\_id\z/, '')
          next unless fixture_id = attributes[reflection]
          if attrs = data[foreign_model.table_name][fixture_id]
            attributes[column.to_s] = attrs['id']
          else
            raise "Cannot find #{fixture_id} for #{references} in #{table}##{record}"
          end
          attributes.delete(reflection)
        end
      else
        # Polymorphic reflection case
        data[table.to_s].each do |record, attributes|
          reflection = column.to_s.gsub(/\_id\z/, '')
          next unless attributes[reflection]
          type_column = reflection + '_type'
          fixture_id, class_name = attributes[reflection].split(/[\(\)\s]+/)[0..1]
          foreign_model = class_name.constantize
          if attrs = data[foreign_model.table_name][fixture_id]
            attributes[column.to_s] = attrs['id']
            attributes[type_column] = foreign_model.name
          else
            raise "Cannot find #{fixture_id} for #{references} in #{table}##{record}"
          end
          attributes.delete(reflection)
        end
      end
    end
    data[table.to_s].each do |record, attributes|
      data[table.to_s][record] = attributes.sort { |a, b| a.first <=> b.first }.inject({}) do |hash, pair|
        hash[pair.first] = pair.second
        hash
      end
    end
  end

  # Write
  Ekylibre::Schema.tables.each do |table, _columns|
    File.open(directory.join("#{table}.yml"), 'wb') do |f|
      f.write data[table].to_yaml
    end
  end

  # Clean
  Clean::Annotations.run(only: :fixtures, verbose: false)
end

.convert_value(value, type = :string) ⇒ Object


340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/fixturing.rb', line 340

def convert_value(value, type = :string)
  value = value.to_s
  value = if type == :float
            value.to_f
          elsif type == :geometry || type == :point || type == :multi_polygon
            Charta.new_geometry(value).to_ewkt
          elsif type == :decimal
            value.to_f
          elsif type == :integer
            value.to_i
          elsif type == :date
            value.to_date
          elsif type == :datetime
            value.to_time(:utc)
          elsif type == :boolean
            (%w(1 t T true yes TRUE).include?(value) ? true : false)
          elsif type == :json || type == :jsonb
            JSON.parse(value)
          else
            puts "Unknown type to parse in fixtures: #{type.inspect}".red unless [:text, :string, :uuid].include?(type)
            value =~ /\A\-\-\-(\s+|\z)/ ? YAML.load(value) : value
          end
  value
end

.current_versionObject


5
6
7
# File 'lib/fixturing.rb', line 5

def current_version
  CSV.read(migrations_file).last.first.to_i
end

.directoryObject


9
10
11
# File 'lib/fixturing.rb', line 9

def directory
  Rails.root.join('test', 'fixtures')
end

.dump(tenant, options = {}) ⇒ Object

Dump data of database into fixtures


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
# File 'lib/fixturing.rb', line 57

def dump(tenant, options = {})
  Ekylibre::Tenant.switch!(tenant)

  migrate(tenant) unless up_to_date?

  if options[:backup]
    backup = "#{directory}~"
    FileUtils.rm_rf(backup)
    FileUtils.cp_r(directory, backup)
  end

  Dir[directory.join('*.yml').to_s].each do |f|
    FileUtils.rm_rf(f)
  end

  version = extract(path: directory)

  # Updates fixtures name with models
  beautify_fixture_ids(path: directory)

  # Clean annotations
  Clean::Annotations.run(only: :fixtures, verbose: false)

  # Dump last schema_migrations into schema_migrations file
  File.open(migrations_file, 'wb') do |f|
    f.write version
  end
end

.extract(options = {}) ⇒ Object

Extract data from DB into given path or test/fixtures by default Returns version of DB (as integer)


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
# File 'lib/fixturing.rb', line 88

def extract(options = {})
  path = options[:path] || directory
  Ekylibre::Schema.tables.each do |table, columns|
    records = {}
    for row in ActiveRecord::Base.connection.select_all("SELECT * FROM #{table} ORDER BY id")
      record = {}
      for attribute, value in row.sort
        if columns[attribute]
          unless value.nil?
            type = columns[attribute].type
            type = columns[attribute].limit[:type] if columns[attribute].limit.is_a?(Hash)
            record[attribute] = convert_value(value, type.to_sym)
          end
        else
          puts "Cannot find column '#{attribute}' in #{table}. Run `rake clean:schema`.".red
        end
      end
      records["#{table}_#{row['id'].rjust(3, '0')}"] = record
    end

    File.open(path.join("#{table}.yml"), 'wb') do |f|
      f.write records.to_yaml.gsub(/[\ \t]+\n/, "\n")
    end
  end

  version = ActiveRecord::Base.connection.select_value("SELECT * FROM #{migrations_table} ORDER BY 1 DESC")
  version.to_i
end

.migrate(tenant, options = {}) ⇒ Object


117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/fixturing.rb', line 117

def migrate(tenant, options = {})
  target = ActiveRecord::Migrator.last_version
  origin = options[:origin] || current_version
  if target != origin
    say 'Migrate fixtures from ' + origin.inspect + ' to ' + target.inspect
    Ekylibre::Tenant.switch(tenant) do
      ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_paths, target)
    end
  else
    say 'No more migrations', :green
  end
end

.migrations_fileObject


13
14
15
# File 'lib/fixturing.rb', line 13

def migrations_file
  directory.join(migrations_table)
end

.migrations_tableObject


17
18
19
# File 'lib/fixturing.rb', line 17

def migrations_table
  'schema_migrations'
end

.reflectionize_keysObject

Reverse of #columnize_keys Fixtures are expected with ids !


218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
# File 'lib/fixturing.rb', line 218

def reflectionize_keys
  # Load and prepare fixtures
  data = {}
  model_ids = {}
  Ekylibre::Schema.tables.each do |table, _columns|
    records = YAML.load_file(directory.join("#{table}.yml"))
    base_model = table.to_s.classify
    counter = {}
    data[table.to_s] = records.values.sort { |a, b| [a['type'] || base_model, a['id']] <=> [b['type'] || base_model, b['id']] }.inject({}) do |hash, attributes|
      model = attributes['type'] ? attributes['type'].underscore.pluralize : table.to_s
      counter[model] ||= 0
      counter[model] += 1
      hash["#{model}_#{counter[model].to_s.rjust(3, '0')}"] = attributes
      hash
    end
  end

  # Convert
  Ekylibre::Schema.tables.each do |table, columns|
    columns.each do |column, definition|
      next unless references = definition[:references]
      if references.is_a?(Symbol)
        # Standard reflection case
        foreign_model = references.to_s.camelcase.constantize
        puts references.inspect.red unless data[foreign_model.table_name]
        data[table.to_s].each do |record, attributes|
          next unless fixture_id = attributes[column.to_s]
          if attrs = data[foreign_model.table_name].detect { |_r, a| a['id'] == fixture_id }
            attributes[column.to_s.gsub(/\_id\z/, '')] = attrs.first
          else
            raise "Cannot find #{foreign_model.name} #{fixture_id} for #{column} in #{table}##{record}"
          end
          attributes.delete(column.to_s)
        end
      else
        # Polymorphic reflection case
        data[table.to_s].each do |record, attributes|
          type_column = column.to_s.gsub(/\_id\z/, '') + '_type'
          next unless (fixture_id = attributes[column.to_s]) && (fixture_type = attributes[type_column])
          foreign_model = fixture_type.constantize
          if attrs = data[foreign_model.table_name].detect { |_r, a| a['id'] == fixture_id && (a['type'] || foreign_model.name) == fixture_type }
            attributes[column.to_s.gsub(/\_id\z/, '')] = "#{attrs.first} (#{fixture_type})"
          else
            raise "Cannot find #{fixture_type}##{fixture_id} for #{column} in #{table}##{record} (#{attributes['id']})"
          end
          attributes.delete(column.to_s)
          attributes.delete(type_column)
        end
      end
    end
  end

  data.each do |table, records|
    records.each do |record, attributes|
      data[table][record] = attributes.delete_if { |k, _v| k == 'id' }.sort { |a, b| a.first <=> b.first }.inject({}) do |hash, pair|
        hash[pair.first] = pair.second
        hash
      end
    end
  end

  # Write
  Ekylibre::Schema.tables.each do |table, _columns|
    File.open(directory.join("#{table}.yml"), 'wb') do |f|
      f.write data[table].to_yaml
    end
  end

  # Clean
  Clean::Annotations.run(only: :fixtures, verbose: false)
end

.restore(tenant, options = {}) ⇒ Object


34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/fixturing.rb', line 34

def restore(tenant, options = {})
  path = options[:path] || directory
  version = options[:version] || current_version
  verbose = !options[:verbose].is_a?(FalseClass)
  Apartment.connection.execute("DROP SCHEMA IF EXISTS \"#{tenant}\" CASCADE")
  Apartment.connection.execute("CREATE SCHEMA \"#{tenant}\"")
  Ekylibre::Tenant.add(tenant)
  Apartment.connection.execute("SET search_path TO '#{tenant}, postgis'")
  Ekylibre::Tenant.migrate(tenant, to: version)
  table_names = tables_from_files(path: path)
  say 'Load fixtures' if verbose
  Ekylibre::Tenant.switch!(tenant)
  ActiveRecord::FixtureSet.reset_cache
  ActiveRecord::FixtureSet.create_fixtures(path, table_names)
  migrate(tenant, origin: version) unless up_to_date?(version: version)
end

.reverse(tenant, steps = 1) ⇒ Object


51
52
53
54
# File 'lib/fixturing.rb', line 51

def reverse(tenant, steps = 1)
  restore(tenant)
  rollback(tenant, steps)
end

.rollback(tenant, steps = 1) ⇒ Object


130
131
132
133
134
135
# File 'lib/fixturing.rb', line 130

def rollback(tenant, steps = 1)
  say "Rollback (Steps count: #{steps})"
  Ekylibre::Tenant.switch(tenant) do
    ActiveRecord::Migrator.rollback(ActiveRecord::Migrator.migrations_paths, steps)
  end
end

.say(text, color = :yellow) ⇒ Object


137
138
139
140
# File 'lib/fixturing.rb', line 137

def say(text, color = :yellow)
  size = text.size
  puts '== ' + text.send(color) + ' ' + '=' * (79 - size - 4) + "\n\n"
end

.tables_from_files(options = {}) ⇒ Object


27
28
29
30
31
32
# File 'lib/fixturing.rb', line 27

def tables_from_files(options = {})
  path = options[:path] || directory
  Dir.glob(path.join('*.yml')).collect do |f|
    Pathname.new(f).basename('.*').to_s
  end.sort
end

.up_to_date?(options = {}) ⇒ Boolean

Returns true if current_version is last DB version

Returns:

  • (Boolean)

22
23
24
25
# File 'lib/fixturing.rb', line 22

def up_to_date?(options = {})
  version = options[:version] || current_version
  version == ActiveRecord::Migrator.last_version
end

.yaml_escape(value, type = :string) ⇒ Object


328
329
330
331
332
333
334
335
336
337
338
# File 'lib/fixturing.rb', line 328

def yaml_escape(value, type = :string)
  value = value.to_s
  value = if type == :float || type == :decimal || type == :integer
            value
          elsif type == :boolean
            (%w(1 t T true yes TRUE).include?(value) ? 'true' : 'false')
          else
            value.to_yaml.gsub(/^\-\-\-\s*/, '').strip
          end
  value
end