Class: Mdb::Database

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, options = {}) ⇒ Database

Returns a new instance of Database.



12
13
14
15
16
17
18
# File 'lib/mdb/database.rb', line 12

def initialize(file, options={})
  file = file.to_path if file.respond_to?(:to_path)
  raise FileDoesNotExistError, "\"#{file}\" does not exist" unless File.exist?(file)
  
  @file = file
  @delimiter = options.fetch :delimiter, '|'
end

Instance Attribute Details

#delimiterObject (readonly)

Returns the value of attribute delimiter.



22
23
24
# File 'lib/mdb/database.rb', line 22

def delimiter
  @delimiter
end

#fileObject (readonly)

Returns the value of attribute file.



22
23
24
# File 'lib/mdb/database.rb', line 22

def file
  @file
end

Instance Method Details

#columns(table) ⇒ Object



32
33
34
# File 'lib/mdb/database.rb', line 32

def columns(table)
  open_csv(table) { |csv| csv.readline.map(&:to_sym) }
end

#each_record(table, &block) ⇒ Object Also known as: each

Yields a hash for each record



47
48
49
50
51
52
53
54
55
56
# File 'lib/mdb/database.rb', line 47

def each_record(table, &block)
  columns = nil
  read_each(table) do |line|
    if columns
      yield Hash[columns.zip(line)]
    else
      columns = line.map(&:to_sym)
    end
  end
end

#read_csv(table) ⇒ Object



38
39
40
41
42
# File 'lib/mdb/database.rb', line 38

def read_csv(table)
  csv = execute "mdb-export -D '%F %T' -d \\| #{file_name} #{table}"
  empty_table!(table) if csv.empty?
  csv
end

#read_records(table) ⇒ Object Also known as: read, []

Returns an array of hashes. Each hash represents a record



62
63
64
65
66
# File 'lib/mdb/database.rb', line 62

def read_records(table)
  hashes = []
  each(table) {|hash| hashes << hash}
  hashes
end

#tablesObject



26
27
28
# File 'lib/mdb/database.rb', line 26

def tables
  @tables ||= execute("mdb-tables -1 #{file_name}").scan(/^\w+$/)
end