lib/dbf/reader.rb in dbf-0.5.3 vs lib/dbf/reader.rb in dbf-0.5.4

- old
+ new

@@ -4,13 +4,10 @@ attr_reader :field_count # An array of DBF::Field records attr_reader :fields - # The total number of records. This number includes records marked as deleted. - attr_reader :record_count - # Internal dBase version number attr_reader :version # Last updated datetime attr_reader :last_updated @@ -22,12 +19,14 @@ attr_reader :memo_block_size # Initialize a new DBF::Reader. # Example: # reader = DBF::Reader.new 'data.dbf' - def initialize(filename) - @in_memory = true + def initialize(filename, options = {}) + options = {:in_memory => true}.merge(options) + + @in_memory = options[:in_memory] @data_file = File.open(filename, 'rb') @memo_file = open_memo(filename) reload! end @@ -35,26 +34,28 @@ def reload! @records = nil get_header_info get_memo_header_info if @memo_file get_field_descriptors + build_db_index end # Returns true if there is a corresponding memo file def has_memo_file? @memo_file ? true : false end # If true, DBF::Reader will load all records into memory. If false, records are retrieved using file I/O. + # You can set this option is set during initialization of the DBF::Reader. Defaults to true. Example: + # reader = DBF::Reader.new 'data.dbf', :in_memory => false def in_memory? @in_memory end - # Tells DBF::Reader whether to load all records into memory. Defaults to true. - # You may need to set this to false if the database is very large in order to reduce memory usage. - def in_memory=(boolean) - @in_memory = boolean + # The total number of active records. + def record_count + @db_index.size end # Returns an instance of DBF::Field for <b>field_name</b>. <b>field_name</b> # can be a symbol or a string. def field(field_name) @@ -237,25 +238,35 @@ # Returns the record at <tt>index</tt> by seeking to the record in the # physical database file. See the documentation for the records method for # information on how these two methods differ. def get_record_from_file(index) - seek_to_record(index) + seek_to_record(@db_index[index]) active_record? ? Record.new(self, @data_file, @memo_file) : nil end def get_all_records_from_file all_records = [] 0.upto(@record_count - 1) do |n| seek_to_record(n) if active_record? all_records << DBF::Record.new(self, @data_file, @memo_file) - else - all_records << nil end end all_records end + def build_db_index + @db_index = [] + @deleted_records = [] + 0.upto(@record_count - 1) do |n| + seek_to_record(n) + if active_record? + @db_index << n + else + @deleted_records << n + end + end + end end end \ No newline at end of file