Class: Mdb::Database
- Inherits:
-
Object
- Object
- Mdb::Database
- Defined in:
- lib/mdb/database.rb
Instance Attribute Summary collapse
-
#delimiter ⇒ Object
readonly
Returns the value of attribute delimiter.
-
#file ⇒ Object
readonly
Returns the value of attribute file.
Instance Method Summary collapse
- #columns(table) ⇒ Object
-
#each_record(table, &block) ⇒ Object
(also: #each)
Yields a hash for each record.
-
#initialize(file, options = {}) ⇒ Database
constructor
A new instance of Database.
- #read_csv(table) ⇒ Object
-
#read_records(table) ⇒ Object
(also: #read, #[])
Returns an array of hashes.
- #tables ⇒ Object
Constructor Details
#initialize(file, options = {}) ⇒ Database
Returns a new instance of Database.
11 12 13 14 15 16 17 |
# File 'lib/mdb/database.rb', line 11 def initialize(file, ={}) file = file.to_path if file.respond_to?(:to_path) raise FileDoesNotExistError, "\"#{file}\" does not exist" unless File.exist?(file) @file = file @delimiter = .fetch :delimiter, "|" end |
Instance Attribute Details
#delimiter ⇒ Object (readonly)
Returns the value of attribute delimiter.
21 22 23 |
# File 'lib/mdb/database.rb', line 21 def delimiter @delimiter end |
#file ⇒ Object (readonly)
Returns the value of attribute file.
21 22 23 |
# File 'lib/mdb/database.rb', line 21 def file @file end |
Instance Method Details
#columns(table) ⇒ Object
31 32 33 34 35 36 37 38 39 40 |
# File 'lib/mdb/database.rb', line 31 def columns(table) open_csv(table) do |csv| line = csv.readline unless line || tables.member?(table.to_s) raise TableDoesNotExistError, "#{table.inspect} does not exist in #{file_name.inspect}" end (line || []).map(&:to_sym) end end |
#each_record(table, &block) ⇒ Object Also known as: each
Yields a hash for each record
53 54 55 56 57 58 59 60 61 62 |
# File 'lib/mdb/database.rb', line 53 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
44 45 46 47 48 |
# File 'lib/mdb/database.rb', line 44 def read_csv(table) csv = execute "mdb-export -D '%F %T' -d \\| #{file_name} #{Shellwords.escape(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
68 69 70 71 72 |
# File 'lib/mdb/database.rb', line 68 def read_records(table) hashes = [] each(table) {|hash| hashes << hash} hashes end |
#tables ⇒ Object
25 26 27 |
# File 'lib/mdb/database.rb', line 25 def tables @tables ||= execute("mdb-tables -1 #{file_name}").scan(/[^\n]+/) end |