Skip to content

Commit

Permalink
Index the records for faster searching
Browse files Browse the repository at this point in the history
  • Loading branch information
desmondmonster committed Jul 25, 2012
1 parent fd8e107 commit aa94e32
Showing 1 changed file with 19 additions and 14 deletions.
33 changes: 19 additions & 14 deletions lib/active_hash/base.rb
Expand Up @@ -11,8 +11,6 @@ class IdError < StandardError

class Base

require 'set'

if respond_to?(:class_attribute)
class_attribute :_data, :dirty
else
Expand Down Expand Up @@ -59,7 +57,7 @@ def data
def data=(array_of_hashes)
mark_dirty
@records = nil
reset_ids
reset_record_index
self._data = array_of_hashes
if array_of_hashes
auto_assign_fields(array_of_hashes)
Expand All @@ -75,7 +73,7 @@ def insert(record)
validate_unique_id(record) if dirty
mark_dirty

ids << record.id
add_to_record_index({ record.id.to_s => @records.length })
@records << record
end

Expand All @@ -88,20 +86,26 @@ def next_id
end
end

def ids
@ids ||= Set.new
def record_index
@record_index ||= {}
end

private :record_index

def reset_record_index
record_index.clear
end

private :ids
private :reset_record_index

def reset_ids
ids.clear
def add_to_record_index(entry)
record_index.merge!(entry)
end

private :reset_ids
private :add_to_record_index

def validate_unique_id(record)
raise IdError.new("Duplicate Id found for record #{record.attributes}") if ids.include?(record.id)
raise IdError.new("Duplicate Id found for record #{record.attributes}") if record_index.has_key?(record.id.to_s)
end

private :validate_unique_id
Expand Down Expand Up @@ -148,7 +152,7 @@ def transaction

def delete_all
mark_dirty
reset_ids
reset_record_index
@records = []
end

Expand All @@ -168,7 +172,8 @@ def find(id, * args)
end

def find_by_id(id)
all.detect { |record| record.id.to_s == id.to_s }
index = record_index[id.to_s]
index and @records[index]
end

delegate :first, :last, :to => :all
Expand Down Expand Up @@ -326,7 +331,7 @@ def base_class
end

def reload
reset_ids
reset_record_index
self.data = _data
mark_clean
end
Expand Down

0 comments on commit aa94e32

Please sign in to comment.