Module: Dbreap::Reap

Defined in:
lib/dbreap/reap.rb

Class Method Summary collapse

Class Method Details

.build_yml(table_name, connection: ActiveRecord::Base.connection) ⇒ Object



5
6
7
8
9
10
11
12
13
# File 'lib/dbreap/reap.rb', line 5

def self.build_yml(table_name, connection: ActiveRecord::Base.connection)
  raw = fetch_rows(table_name, connection:)

  rows = raw.each_with_index.with_object({}) do |(row, i), accum|
    key = "#{table_name}_#{format('%03d', i + 1)}"
    accum[key] = row.transform_values { |v| cast_value(v) }
  end
  Psych.dump(rows, line_width: -1)
end

.cast_value(value) ⇒ Object



22
23
24
25
26
27
28
# File 'lib/dbreap/reap.rb', line 22

def self.cast_value(value)
  return value unless value.is_a?(String) && value.match?(/\A[\[{]/)

  JSON.parse(value)
rescue JSON::ParserError
  value
end

.fetch_rows(table_name, connection: ActiveRecord::Base.connection) ⇒ Object



15
16
17
18
19
20
# File 'lib/dbreap/reap.rb', line 15

def self.fetch_rows(table_name, connection: ActiveRecord::Base.connection)
  quoted = connection.quote_table_name(table_name)
  connection.select_all("SELECT * FROM #{quoted} ORDER BY id")
rescue ActiveRecord::StatementInvalid
  connection.select_all("SELECT * FROM #{quoted} ORDER BY 1")
end

.write_fixture(table_name, root: Rails.root, env: Rails.env) ⇒ Object



30
31
32
33
34
35
# File 'lib/dbreap/reap.rb', line 30

def self.write_fixture(table_name, root: Rails.root, env: Rails.env)
  path = "#{root}/db/fixtures/#{env}/#{table_name}.yml"
  yaml = build_yml(table_name)
  File.write(path, yaml)
  puts "Reaped #{table_name}"
end