Active entry as a function in an array instance variable

I would like to write a module that provides active writing such as functionality in 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 id
          self
          #=> #<Array..>  but I need #<Container..>
        end
     end
     super(*args)
  end
end

      

The problem is that I need a Container object in these methods. Any reference to self will return an array, not a Container object.

Is there a way to do this?

Thanks!

+2


a source to share


2 answers


Does something like this work for you?

class Container
  attr_accessor :elements

  def initialize
    @elements = ContainerElements.new
  end
end

class ContainerElements < Array

  def find_by_id(id)
    self.find {|g| g.id == id }
  end

end

      

So I am creating a container class and ContainerElements that inherits from Array, with a (specific) find_by_id method added. If you really want to name it find

, you need alias

it.



Sample code:

class ElemWithId
  attr_accessor :id
  def initialize(value)
    @id = value
  end
end

cc = Container.new
cc.elements << ElemWithId.new(1)
cc.elements << ElemWithId.new(5)

puts "elements = #{cc.elements} "
puts "Finding: #{cc.elements.find_by_id(5)} "

      

Hope it helps ...

+1


a source


Your best approach might be to work with a Hash class that already has operations like lookup by id. In particular, the fetch method can help you.



0


a source







All Articles