2010-05-10 38 views
2

我想编写一个模块,它提供了有关数组实例变量的活动记录功能。其使用的活动记录像数组实例变量的功能

例子是

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 

的问题是,我需要这些方法中的容器对象。对self的任何引用都会返回Array,而不是Container对象。

有没有办法做到这一点?

谢谢!

回答

1

会这样的工作吗?

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 

所以我创建一个容器类,以及从阵列继承,添加有(特定)find_by_id方法的ContainerElements。 如果你真的想叫它find你需要alias吧。

示例代码如下:

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)} " 

希望这有助于...

0

您的最佳方法可能是使用类似Hash的类,该类有像id查找那样的操作。特别是,fetch方法可能会帮助你。

+0

哈希真的不是一个选项。它需要像一个数组那样工作,因为代码库使用它。 – stellard 2010-05-10 23:03:01

+0

我可能会误解你需要什么,但是不能把hash_object.values()传递给需要用数组处理的事情吗? – corprew 2010-05-11 16:44:43