Skip to content

Instantly share code, notes, and snippets.

@earlonrails
Created September 9, 2011 21:27
Show Gist options
  • Save earlonrails/1207384 to your computer and use it in GitHub Desktop.
Save earlonrails/1207384 to your computer and use it in GitHub Desktop.
Dynamic Fields using mongoid. Use Mongoid to store a random size hash.
hsh = {}; (0..rand(5)).each { |idx| hsh["val#{idx}"] = [rand(5),rand(5),(idx % 2 == 0) ? hsh.clone: rand(5)] * (rand(2)+1) }; hsh
my_taco = TacoHash.new
my_taco.write_attributes(hsh)
my_taco.save
my_new_taco = TacoHash.last
#<TacoHash _id: 4e6a5a031a2c840d83000002, val0: [2, 0, {}, 2, 0, {}], val1: [2, 1, 2], val2: [1, 4, {"val0"=>[2, 0, {}, 2, 0, {}], "val1"=>[2, 1, 2]}], val3: [1, 1, 1, 1, 1, 1], val4: [4, 2, {"val0"=>[2, 0, {}, 2, 0, {}], "val1"=>[2, 1, 2], "val2"=>[1, 4, {"val0"=>[2, 0, {}, 2, 0, {}], "val1"=>[2, 1, 2]}], "val3"=>[1, 1, 1, 1, 1, 1]}, 4, 2, {"val0"=>[2, 0, {}, 2, 0, {}], "val1"=>[2, 1, 2], "val2"=>[1, 4, {"val0"=>[2, 0, {}, 2, 0, {}], "val1"=>[2, 1, 2]}], "val3"=>[1, 1, 1, 1, 1, 1]}]>
my_new_taco.val0
require 'mongoid'
# MongoDB ENV vars
# export MONGOID_HOST='localhost'
# export MONGOID_PORT='27017'
# export MONGOID_USERNAME='billy'
# export MONGOID_PASSWORD='iambilly'
# export MONGOID_DATABASE='billys_db'
File.open(File.join(RAILS_ROOT, 'config/mongodb.yml'), 'r') do |f|
@settings = YAML.load(f)[RAILS_ENV]
end
port = @settings["port"].nil? ? Mongo::Connection::DEFAULT_PORT : @settings["port"]
connection = Mongo::Connection.new(@settings["host"], port )
Mongoid.database = connection.db(@settings["database"])
Mongoid.configure do |config|
config.allow_dynamic_fields = true
end
class TacoHash
include Mongoid::Document
field :tacos, :type => Hash
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment