3

I'm moving from using Module#alias_method_chain to Module#prepend.

But there is one situation where I cannot achieve the same functionality

Suppose I have a library code (two libraries actually, one of which enhances another)

# Library 1
object = Object.new
# Library 2
module Extender
  def random_number
    4
  end
end
object.extend Extender

object.random_number # => 4

Now, say I want object#random_number to return 5. My old code was

Extender.class_eval do
  def random_number_with_magic
    random_number_without_magic + 1
  end
  alias_method_chain :random_number, :magic
end

object.random_number # => 5

To mimic this using Module#prepend

module Prepender
  def random_number
    super + 1
  end
end
Extender.prepend Prepender

object.random_nuber # => still 4!

The desired results could be achieved by two approaches

  • call Extender.prepend Prepender before object.extend Extender (not an option since I cannot control the code in external libraries)
  • call object.extend Prepender instead of Extender.prepend Prepender (not an option since object object is not visible outside)

Any advice?

Roman Usherenko
  • 4,659
  • 4
  • 17
  • 14
  • _Sidenote:_ there are no “invisible outside” objects in ruby. – Aleksei Matiushkin Jan 21 '16 at 14:51
  • riight. what i meant to say was 'easily visible' =) besides in this particular situation several similar objects end up in an array, and there's no easy way to distinguish between them and choose the right one to extend – Roman Usherenko Jan 21 '16 at 14:55

0 Answers0