| 
									
										
										
										
											2015-02-12 13:01:05 +03:00
										 |  |  | 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! | 
					
						
							| 
									
										
										
										
											2015-10-26 12:04:01 +03:00
										 |  |  |           hash = record.to_mongo_hash | 
					
						
							|  |  |  |           hash["created_at"] = Time.now.to_i | 
					
						
							|  |  |  |           collection.insert(hash) | 
					
						
							| 
									
										
										
										
											2015-07-30 02:22:54 +03:00
										 |  |  |           record | 
					
						
							| 
									
										
										
										
											2015-02-12 13:01:05 +03:00
										 |  |  |         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 |