Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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