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, &block) ⇒ 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 |
# 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, &block) ⇒ Object Also known as: each
Yields a hash for each record
48 49 50 51 52 53 54 55 56 57 |
# 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 |
#read_csv(table, &block) ⇒ Object
39 40 41 42 43 |
# 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) ⇒ Object Also known as: read, []
Returns an array of hashes. Each hash represents a record
63 64 65 66 67 |
# File 'lib/mdb/database.rb', line 63 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 |