Active Record like functionality on array instance variable

Posted by rube_noob on Stack Overflow See other posts from Stack Overflow or by rube_noob
Published on 2010-05-10T16:54:49Z Indexed on 2010/05/10 20:04 UTC
Read the original article Hit count: 269

I would like to write a module that provides active record like functionality on an array instance variable.

Examples of its use would be

x = Container.new
x.include(ContainerModule)
x.elements << Element.new
x.elements.find id

module ContainerModule
   def initialize(*args)
     @elements = []
     class << @elements
        def <<(element)
          #do something with the Container...
          super(element)         
        end

        def find(id)
          #find an element using the Container's id
          self
          #=> #<Array..>  but I need #<Container..>
        end
     end
     super(*args)
  end
end

The problem is that I need the Container object within these methods. Any reference to self will return the Array, not the Container object.

Is there any way to do this?

Thanks!

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about activerecord