32 lines
		
	
	
		
			922 B
		
	
	
	
		
			Ruby
		
	
	
	
	
	
		
		
			
		
	
	
			32 lines
		
	
	
		
			922 B
		
	
	
	
		
			Ruby
		
	
	
	
	
	
|  | require 'lib/string_helper' | ||
|  | 
 | ||
|  | module Connectors | ||
|  |   module Helpers | ||
|  |     module InsertCommand | ||
|  | 
 | ||
|  |       # when included, this module adds method #insert and alias for it. | ||
|  |       # Alias name depends on base class name. | ||
|  |       # We need this alias to forward methods from MongoConnector to resources connectors. | ||
|  | 
 | ||
|  |       def self.included(base) | ||
|  |         resource_name = StringHelper.underscore_class(base) | ||
|  |         method_name = "#{resource_name}_insert".to_sym | ||
|  |         alias_method method_name, :insert | ||
|  |       end | ||
|  | 
 | ||
|  |       def insert(record) | ||
|  |         begin | ||
|  |           record.validate! | ||
|  |           collection.insert(record.to_mongo_hash) | ||
|  |         rescue Mongo::OperationFailure => e | ||
|  |           if e.message =~ /^11000/ | ||
|  |             resource_name = StringHelper.underscore_class(record.class) | ||
|  |             raise InvalidRecord.new("Duplicate key error: #{resource_name} with id '#{record.id}'") | ||
|  |           end | ||
|  |         end | ||
|  |       end | ||
|  | 
 | ||
|  |     end | ||
|  |   end | ||
|  | end |