Created
July 3, 2012 04:54
-
-
Save adamgotterer/3037775 to your computer and use it in GitHub Desktop.
A Rake task to create Mongoid indexes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Based on: http://vikinghammer.com/2012/05/16/rake-task-mongoid-index/ | |
# Usage: rake mongoid:create_indexes[ENV_TYPE_HERE] | |
require 'mongoid' | |
require 'logger' | |
logger = Logger.new($stdout) | |
ROOT = File.expand_path('.', File.dirname(__FILE__)) | |
namespace :mongoid do | |
task :create_indexes, :environment do |t, args| | |
def determine_model(path) | |
path =~ /(.*)\/(.*).rb/ | |
$2.camelize.constantize | |
end | |
unless args[:environment] | |
logger.fatal "Mongoid: Must provide an environment" | |
exit | |
end | |
yaml = YAML.load_file("config/mongoid.yml") | |
env_info = yaml[args[:environment]] | |
unless env_info | |
logger.fatal "Mongoid: Unknown environment" | |
exit | |
end | |
Mongoid.configure do |config| | |
config.from_hash(env_info) | |
end | |
Dir.glob(File.join(ROOT, 'models', '*.rb')).each do |model| | |
require model | |
klass = determine_model(model) | |
if klass.ancestors.include?(Mongoid::Document) | |
klass.create_indexes | |
logger.info "Mongoid: Indexes processed for \"#{klass.class.name}\"" | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment