lib/mongo-fixture.rb in mongo-fixture-0.0.1 vs lib/mongo-fixture.rb in mongo-fixture-0.0.2
- old
+ new
@@ -23,10 +23,11 @@
# and a Mongo::DB connection
def initialize fixture = nil, connection = nil, option_push = true
load fixture if fixture
@connection = connection if connection
+ @inserted = []
push if fixture && connection && option_push
end
# Loads the fixture files into this instance
def load fixture
@@ -90,37 +91,62 @@
@data.each do |collection, matrix|
matrix.each do |element, values|
begin
@connection[collection].insert simplify values.to_hash
+ @inserted ||= Array.new
+ @inserted << collection
rescue MissingProcessedValueError => m
rollback
raise MissingProcessedValueError, "In record '#{element}' to be inserted into '#{collection}', the processed value of field '#{m.field}' is missing, aborting"
end
end
end
end
# Simplifies the hash in order to insert it into the database
- # (Note: I'm well aware that this functionality belongs in a dependency,
- # specially now that is repeated here and in Sequel::Fixture)
+ # Resolves external references and flattens the values that provide alternatives
# @param [Hash] the hash to be processed
def simplify the_hash
the_returned_hash = {}
the_hash.each do |key, value|
if value.is_a? Hash
- unless value.has_key? :processed
- raise MissingProcessedValueError.new "The processed value to insert into the db is missing from the field '#{key}', aborting", key
+
+ # If no alternative matches the name of a collection, look for a :processed value
+ if (value.keys & @data.keys).empty?
+ unless value.has_key? :processed
+ raise MissingProcessedValueError.new "The processed value to insert into the db is missing from the field '#{key}', aborting", key
+ end
+ the_returned_hash[key] = value[:processed]
+ else
+
+ # Does any of the options hold a record named after the value of the option?
+ options = value.keys & @data.keys
+ actual_option = options.each do |option|
+ break option if @data[option].has_key? value[option].to_sym
+ end
+
+ unless data_was_inserted_in? actual_option
+ insert_data_for actual_option
+ end
+ the_returned_hash[key] = @connection[actual_option].find( @data[actual_option][value[actual_option].to_sym] ).first[:_id]
end
- the_returned_hash[key] = value[:processed]
else
the_returned_hash[key] = value
end
end
return the_returned_hash
end
+ # Inserts the collection data into the database
+ def insert_data_for collection
+ @data[collection].each do |key, record|
+ @connection[collection].insert record
+ end
+ @inserted << collection
+ end
+
# Empties the collections, only if they were empty to begin with
def rollback
begin
check
@@ -142,8 +168,13 @@
attr_accessor :field
def initialize message, field = nil
@field = field
super message
end
- end
+ end
+
+ private
+ def data_was_inserted_in? collection
+ @inserted.include? collection
+ end
end
end