Created
October 22, 2010 23:58
-
-
Save iamnader/641569 to your computer and use it in GitHub Desktop.
Mongoid Set Defaults Rake Task
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
require 'config/environment' | |
require 'mongo' | |
namespace :mongoid do | |
desc 'Update defaults' | |
task :defaults do | |
db = Mongoid.config.master | |
models.each do |m| | |
m = eval m | |
if !m.embedded? | |
fields_with_defaults = m.fields.select {|k,v| v.options.include?(:default)} | |
fields_with_defaults.each do |f| | |
field_name = f[0] | |
default_value = f[1].options[:default] | |
field_type = f[1].options[:type] | |
if valid_mongo_type(field_type) | |
result = db.collection(m.collection.name).update({field_name => {'$exists' => false}}, {'$set' => {field_name => default_value}}, :multi => true, :safe => true) | |
puts result | |
end | |
end | |
end | |
end | |
end | |
end | |
def models | |
Module.constants.select do |constant_name| | |
constant = eval constant_name | |
if not constant.nil? and constant.is_a? Class and constant.included_modules.include? Mongoid::Document | |
constant | |
end | |
end | |
end | |
def valid_mongo_type(t) | |
[Array, BigDecimal, Boolean, Date, DateTime, Float, Hash, Integer, String, Symbol, Time, BSON::ObjectId].include?(t) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment