Skip to content

A Mongoid Hash extension enabling "indifferent access" so you can access keys using Strings or Symbols.

License

Notifications You must be signed in to change notification settings

mindscratch/mongoid-indifferent-access

Repository files navigation

Mongoid Indifferent Access Build Status

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.

Installation

The preferred installation method is by adding mongoid-indifferent-access to your Gemfile:

gem "mongoid-indifferent-access", require: "mongoid_indifferent_access"

The require is important. The gem name has hyphens but the directories use underscores (my bad), so Bundler can't figure out what to load exactly, so this helps it out.

Usage

Before

Notice the nil values when the Hash values are fetched using Symbols.

class QueryResult
  include Mongoid::Document

  field :data, type: Hash
end

# create a QueryResult
QueryResult.create(data: {name: "google", value: 1.32})

# fetch it back from the database
result = QueryResult.first

# check its values
puts result.data["name"]  # => "google"
puts result.data[:value]  # => nil
puts result.data[:name]   # => nil

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

# create a QueryResult
QueryResult.create(data: {name: "google", value: 1.32})

# fetch it back from the database
result = QueryResult.first

# check its values
puts result.data["name"]  # => "google"
puts result.data[:value]  # => 1.32
puts result.data[:name]   # => "google"
puts result.data["value"] # => 1.32

Contributors

I'd like to give a special shout out to those people who've submitted pull requests (which have been approved and merged):

About

A Mongoid Hash extension enabling "indifferent access" so you can access keys using Strings or Symbols.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •