35 lines
1006 B
Ruby
35 lines
1006 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!
|
|
hash = record.to_mongo_hash
|
|
hash["created_at"] = Time.now.to_i
|
|
collection.insert(hash)
|
|
record
|
|
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
|