Mongoid Indifferent Access
A Mongoid Hash extension enabling "indifferent access" so you can access keys using Strings or Symbols.
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. Instead, by relying on ActiveSupport all Hashes can be
accessed using whichever approach suites the developer.
Ruby/JRuby
Thanks to travis-ci this gem is tested against Ruby 1.9.3 and JRuby 1.6.7.
It should also continue work with Ruby 1.9.2 only if you're using Mongoid 2.4.x. As of Mongoid 3.x, Ruby 1.9.3 or newer is
required.
Usage
Before
Notice the nil
values when the Hash values are fetched using Symbols.
class QueryResult
include Mongoid::Document
field :data, type: Hash
end
QueryResult.create(data: {name: "google", value: 1.32})
result = QueryResult.first
puts result.data["name"]
puts result.data[:value]
puts result.data[:name]
After
Notice the values in the Hash can be accessed using Strings or Symbols.
class QueryResult
include Mongoid::Document
include Mongoid::Extensions::Hash::IndifferentAccess
field :data, type: Hash
end
QueryResult.create(data: {name: "google", value: 1.32})
result = QueryResult.first
puts result.data["name"]
puts result.data[:value]
puts result.data[:name]
puts result.data["value"]
Contributors
I'd like to give a special shout out to those people who've submitted pull requests (which have been approved and merged):