Created
January 25, 2010 14:00
-
-
Save charly/285877 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Mongoid | |
def self.included(base) | |
base.extend NoProxyAssociation | |
end | |
# This little piece of codes creates an author method in Book | |
# which instanciates an anonymous class with Author included! | |
# def author | |
# klass = Class.new do | |
# include Book::Author | |
# end | |
# return klass.new | |
# end | |
module NoProxyAssociation | |
def embed_one(embeded, opt={}) | |
parent_class = self.to_s | |
define_method(embeded) do | |
Class.new { include eval("#{parent_class}::#{embeded.to_s.capitalize}") }.new | |
end | |
end | |
end | |
end | |
# model/book.rb | |
class Book | |
include Mongoid | |
embed_one :author, :sync => true | |
embed_one :picture | |
module Author | |
include Mongoid | |
embed_one :address | |
def name()"Nabokov";end | |
module Address | |
def city()"Paris";end | |
end | |
end | |
module Picture | |
def filename()"/images/books/ada.jpg";end | |
end | |
end | |
book = Book.new | |
puts book.author.name # => Nabokov | |
puts book.picture.filename # => /images/books/ada.jpg | |
puts book.author.address.city # => Paris |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment