Skip to content

Instantly share code, notes, and snippets.

@charly
Created January 25, 2010 14:00
Show Gist options
  • Select an option

  • Save charly/285877 to your computer and use it in GitHub Desktop.

Select an option

Save charly/285877 to your computer and use it in GitHub Desktop.

Revisions

  1. charly revised this gist Jan 25, 2010. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion noproxy-association.rb
    Original file line number Diff line number Diff line change
    @@ -44,6 +44,6 @@ def filename()"/images/books/ada.jpg";end
    end

    book = Book.new
    puts book.author.name # => ada
    puts book.author.name # => Nabokov
    puts book.picture.filename # => /images/books/ada.jpg
    puts book.author.address.city # => Paris
  2. charly created this gist Jan 25, 2010.
    49 changes: 49 additions & 0 deletions noproxy-association.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    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 # => ada
    puts book.picture.filename # => /images/books/ada.jpg
    puts book.author.address.city # => Paris