class Mdb::Database
Attributes
delimiter[R]
file[R]
Public Class Methods
new(file, options={})
click to toggle source
# File lib/mdb/database.rb, line 11 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
Public Instance Methods
columns(table)
click to toggle source
# File lib/mdb/database.rb, line 31 def columns(table) open_csv(table) do |csv| (csv.readline || []).map(&:to_sym) end end
each_record(table) { |Hash| ... }
click to toggle source
Yields a hash for each record
# File lib/mdb/database.rb, line 48 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
Also aliased as: each
read_csv(table, &block)
click to toggle source
# File lib/mdb/database.rb, line 39 def read_csv(table, &block) table = table.to_s raise TableDoesNotExistError, "#{table.inspect} does not exist in #{file_name.inspect}" unless tables.member?(table) execute "mdb-export -D '%F %T' -d #{Shellwords.escape(delimiter)} #{file_name} #{Shellwords.escape(table)}", &block end
read_records(table)
click to toggle source
Returns an array of hashes. Each hash represents a record
# File lib/mdb/database.rb, line 63 def read_records(table) hashes = [] each(table) {|hash| hashes << hash} hashes end
tables()
click to toggle source
# File lib/mdb/database.rb, line 25 def tables @tables ||= execute("mdb-tables -1 #{file_name}").scan(/[^\n]+/) end
Private Instance Methods
execute(command) { |file| ... }
click to toggle source
# File lib/mdb/database.rb, line 106 def execute(command) file = Tempfile.new("mdb") unless system "#{command} > #{file.path} 2> /dev/null" raise MdbToolsNotInstalledError if $?.exitstatus == 127 raise Error, "#{command[/^\S+/]} exited with status #{$?.exitstatus}" end return file.read unless block_given? yield file ensure file.close file.unlink end
file_name()
click to toggle source
# File lib/mdb/database.rb, line 92 def file_name Shellwords.escape(file) end
open_csv(table) { |csv(file, col_sep: delimiter)| ... }
click to toggle source
# File lib/mdb/database.rb, line 98 def open_csv(table) read_csv(table) do |file| yield CSV.new(file, col_sep: delimiter) end end
read_each(table) { |line| ... }
click to toggle source
# File lib/mdb/database.rb, line 77 def read_each(table, &block) count = 0 open_csv(table) do |csv| while line = csv.readline yield line count += 1 end end count end