Skip to content

Instantly share code, notes, and snippets.

@VishalTaj
Last active April 11, 2019 14:01
Show Gist options
  • Save VishalTaj/aacede9bc065df5ec4fd8e811b06015e to your computer and use it in GitHub Desktop.
Save VishalTaj/aacede9bc065df5ec4fd8e811b06015e to your computer and use it in GitHub Desktop.
A Database Backup module for MongoId in Rails
require 'slack'
##################################################################
# This module take cares of Database backups #
# #
# Note: please add and configure slack lib which you get in my #
# gist list to enable slack configration #
##################################################################
module DbBackup
mattr_reader :directory_name do 'db_backups' end
mattr_accessor :name
def self.generate_name(name="backup")
self.name = "#{name}-#{Time.now.strftime("%Y-%m-%dT%H-%M-%S")}"
end
def self.compress(cmd)
Dir.chdir() {
FileUtils.mkdir_p(directory_name) unless File.directory?(directory_name)
Dir.chdir(directory_name) {
%x[#{cmd}]
compressed_file_name = generate_name + '.tar.gz'
cmd = 'tar -zcvf ' + compressed_file_name +' ' + "dump"
%x[#{cmd}]
%x[rm -r dump]
if File.exists?(compressed_file_name)
Slack.notify(message: "DbBackup: Successfully generated backup for #{Rails.env} locate file name #{compressed_file_name}")
else
Slack.notify(message: "DbBackup: Some thing went wrong #{Rails.env}", status: :error)
end
}
}
end
module MongoDb
def self.backup
Slack.notify(message: "DbBackup: Started Backup #{Rails.env}", status: :info)
config = Mongoid::Config.clients[:default]
host = config[:host]
database = config[:database]
username = config[:username]
password = config[:password]
host = "localhost" if !host.present?
cmd = "mongodump"
cmd << " -h #{host}" if host.present?
cmd << " -d #{database}" if database.present?
cmd << " -u #{username}" if username.present?
cmd << " -p #{password}" if password.present?
self.parent.compress(cmd)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment