How to hook to an Array instance in a Ruby module

by Frank

On some project we needed to create a module containing an Array attribute. We wanted to hook onto some of the methods of this particular Array instance to call our own code. Here is how we did it:

module TheModule
  attr_reader :items
  def initialize(*args)
    @items = []

    def @items.<<(item)
      super
      "You added the item #{item} with <<!"
    end

    def @items.push(item)
      super
      "You added the item #{item} with push!"
    end
    super
  end
end

class TheClass
  include TheModule
end

And now the output:

x = TheClass.new
x.items   # => []
x.items << 'blue' # => You added the item 'blue' with <<!
x.items.push 'orange' # => You added the item 'orange' with push!
x.items # => ["blue", "orange"]
Bookmark this post : These icons link to social bookmarking sites where readers can share and discover new web pages.
  • DZone
  • Reddit
  • del.icio.us
  • Digg
  • Furl
  • Technorati
  • StumbleUpon