Skip to content

Instantly share code, notes, and snippets.

@mindscratch
Created February 28, 2012 13:19
Show Gist options
  • Save mindscratch/1932521 to your computer and use it in GitHub Desktop.
Save mindscratch/1932521 to your computer and use it in GitHub Desktop.
mongoid hash extension
# BSON stores document keys as strings, so Hash keys are strings
# when going into MongoDB and coming out. This extension allows
# a developer to not worry as to whether or not the keys are
# Strings or Symbols.
#
# This requires Mongoid 2.4.3+ and Rails 3.
#
# Instead of needing Rails you could just require ActiveSupport. In your Gemfile (or .gemspec)
# gem "activesupport", ">= 3.0.0"
#
# In your code:
# require 'active_support/hash_with_indifferent_access'
#
module MongoidHashSupport
def self.included(klass)
klass.class_eval do
# @override Mongoid::Field
def self.field(name, options={})
field = super
if options.fetch(:type, nil) == Hash
getter_name = name.is_a?(Symbol) ? name : name.intern
setter_name = "#{getter_name}=".intern
define_method(getter_name) do
val = super
unless val.nil? || val.is_a?(HashWithIndifferentAccess)
wrapped_hash = val.with_indifferent_access
self.send(setter_name, wrapped_hash)
val = wrapped_hash
end
val
end
define_method(setter_name) do |hash|
unless hash.nil? || hash.is_a?(HashWithIndifferentAccess)
hash = hash.with_indifferent_access
end
super(hash)
end
end
field
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment