Skip to content

Instantly share code, notes, and snippets.

@kke
Created January 20, 2012 13:11
Show Gist options
  • Select an option

  • Save kke/1647337 to your computer and use it in GitHub Desktop.

Select an option

Save kke/1647337 to your computer and use it in GitHub Desktop.
class User
include Mongoid::Document
[:street_address, :phone_number, :email_address].each do |f|
embeds_many f.to_s.pluralize.to_sym do
def [](key)
detect {|e| e.name.eql?(key.to_s)} || build(:name => key.to_s)
end
end
define_method f do
send(f.to_s.pluralize).send('[]', :primary)
end
end
end
:001> u=User.new
=> #<User _id: 4f14134a0096044a70000001, _type: nil >
:002> u.email_address
=> #<EmailAddress _id: 4f1966a50096046eb7000003, _type: nil, name: "primary", email_address: nil>
:003> u.email_addresses[:secondary].email_address = '[email protected]'
=> "[email protected]"
:004> u.email_addresses
=> [#<EmailAddress _id: 4f1966a50096046eb7000003, _type: nil, name: "primary", email_address: nil>, #<EmailAddress _id: 4f1967120096046eb7000004, _type: nil, name: "secondary", email_address: "[email protected]">]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment