Class: SeedingUtils::Table

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Table



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

def initialize(name)
  @conn = SeedingUtils.connection
  self.name = name
  self.quoted_name = PG::Connection.quote_ident(name)
end

Instance Attribute Details

#nameObject

Returns the value of attribute name.



25
26
27
# File 'lib/seeding_utils.rb', line 25

def name
  @name
end

#quoted_nameObject

Returns the value of attribute quoted_name.



25
26
27
# File 'lib/seeding_utils.rb', line 25

def quoted_name
  @quoted_name
end

Instance Method Details

#dump(io) ⇒ Object

Expects an open IO object for writing.



55
56
57
58
59
60
61
62
# File 'lib/seeding_utils.rb', line 55

def dump(io)
  @conn.exec %{COPY #{quoted_name} TO STDOUT WITH (FORMAT 'binary')}
  while row = @conn.get_copy_data do
    io.write(row)
  end
  io.rewind
  return io
end

#load(io) ⇒ Object

Expects an open IO object for reading.



65
66
67
68
69
70
71
72
# File 'lib/seeding_utils.rb', line 65

def load(io)
  @conn.exec %{DELETE FROM #{quoted_name}}
  @conn.exec %{COPY #{quoted_name} FROM STDIN WITH (FORMAT 'binary')}
  while data = io.read(256)
    @conn.put_copy_data(data)
  end
  @conn.put_copy_end
end

#seed(cache_file = nil, &block) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/seeding_utils.rb', line 33

def seed(cache_file = nil, &block)
  path = Pathname(cache_file.to_s)
  return seed_uncached(&block) if cache_file.nil?
  if path.file?
    puts %{-- Loading #{name} seeds from cache}
    @conn.exec %{DELETE FROM #{quoted_name}}
    load path.open 'r:binary'
  elsif block_given?
    seed_uncached(&block)
    path.open 'w:binary' do |io|
      dump(io)
    end
  end
end

#seed_uncached(&block) ⇒ Object



48
49
50
51
# File 'lib/seeding_utils.rb', line 48

def seed_uncached(&block)
  puts %{-- Loading #{name} seeds without cache}
  yield
end