Skip to content

Instantly share code, notes, and snippets.

@jzajpt
Forked from fcoury/mongomapper_polymorphic.rb
Created February 22, 2010 23:30
Show Gist options
  • Save jzajpt/311661 to your computer and use it in GitHub Desktop.
Save jzajpt/311661 to your computer and use it in GitHub Desktop.
require 'mongomapper'
class Media
include MongoMapper::EmbeddedDocument
key :file, String
end
class Video < Media
key :length, Integer
end
class Image < Media
key :width, Integer
key :height, Integer
end
class Music < Media
key :bitrate, String
end
class Catalog
include MongoMapper::Document
many :medias, :polymorphic => true
end
catalog = Catalog.new
catalog.medias = [
Video.new("file" => "video.mpg", "length" => 3600),
Music.new("file" => "music.mp3", "bitrate" => "128kbps"),
Image.new("file" => "image.png", "width" => 800, "height" => 600)
]
catalog.save #=> true
from_db = Catalog.find(catalog.id)
from_db.medias.size #=> 3
from_db.medias[0].file #=> "video.mpg"
from_db.medias[0].length #=> 3600
from_db.medias[1].file #=> "music.mp3"
from_db.medias[1].bitrate #=> "128kbps"
from_db.medias[2].file #=> "image.png"
from_db.medias[2].width #=> 800
from_db.medias[2].height #=> 600
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment