Class: HasAlterEgo::Dumper

Inherits:
Object
  • Object
show all
Defined in:
lib/has_alter_ego/dumper.rb

Class Method Summary collapse

Class Method Details

.dumpObject


3
4
5
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
# File 'lib/has_alter_ego/dumper.rb', line 3

def self.dump
  raise "You need to pass a MODEL=<model name> argument to rake" if ENV["MODEL"].blank?
  klaas = ENV["MODEL"].constantize

  yml_file = File.join(Rails.root.to_s, "db", "fixtures", "alter_egos", klaas.table_name + ".yml")
  yml = {}
  if File.exists?(yml_file)
    File.open(yml_file) do |yf|
      yml = YAML::load( yf )
    end
  end

  puts yml.inspect
  klaas.all.each do |o|
    key = o[klaas.primary_key]
    yml[key] ||= {}
    o.attributes.keys.each do |a|
      next if a == klaas.primary_key
      yml[key][a] = o[a]
    end
    o.build_alter_ego unless o.alter_ego
    o.alter_ego.state = 'default'
    o.save_without_alter_ego
  end
  File.open(yml_file, File::WRONLY|File::TRUNC|File::CREAT) do |yf|
    yf.write yml.to_yaml
  end
end