Skip to content

Instantly share code, notes, and snippets.

@kwiest
Created October 16, 2010 18:47
Show Gist options
  • Save kwiest/630148 to your computer and use it in GitHub Desktop.
Save kwiest/630148 to your computer and use it in GitHub Desktop.
Dynamic keys for MongoMapper
class AnalysisItem
include MongoMapper::EmbeddedDocument
key :name, String
key :value, String
end
class Record
include MongoMapper::Document
many :anaylsis_items
def items
@items ||= AnalysisItemProxy.new(analysis_items)
end
end
class AnalysisItemProxy
def intialize(items)
items.each do |i|
self.class.send(:define_method, i.name.downcase) { i.value }
self.class.send(:define_method, "#{i.name.downcase}=") do |v|
i.value = v
i.save
end
end
end
end
a1 = AnaylsisItem.create(:name => "Mongo", :value => "Sweet")
a2 = AnaylsisItem.create(:name => "Foo", :value => "Bar")
r = Record.new
r.analysis_items << a1
r.analysis_items << a2
r.save
r.items.mongo
#=> "Sweet"
r.items.foo
#=> "Bar"
r.items.foo = "Baz"
r.items.foo
#=> "Baz"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment