Skip to content

Instantly share code, notes, and snippets.

@obfusk
Created February 16, 2013 01:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save obfusk/4964940 to your computer and use it in GitHub Desktop.
Save obfusk/4964940 to your computer and use it in GitHub Desktop.
obfusk-data w/ mongoid
require 'obfusk/data/hash'
require 'mongoid'
Mongoid.load! "#{ Dir.home }/tmp/_/mongoid.yml", :development
module ValidMongoid
module ClassMethods
def data (*a, &b)
self::ValidHash.data(*a, &b)
end
def union (*a, &b)
self::ValidHash.union(*a, &b)
end
def instantiate (*a, &b)
doc = super
attrs = doc.instance_variable_get :@attributes
valid = self::ValidHash.new attrs
doc.instance_variable_set :@attributes, valid
end
end
def self.included (base)
base.extend ClassMethods
base.class_eval do
const_set :ValidHash, Class.new(Obfusk::Data::ValidHash)
def initialize (*a, &b)
super
@attributes = self.class::ValidHash.new @attributes
end
end
end
end
class Foo
include Mongoid::Document
include ValidMongoid
# field :foo
# field :bar
data do
field %w{ _id foo bar }, []
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment