Is there any way to refine some class' initialize method in Ruby?

Viewed 222

I'm trying to do something like this:

module RefinedHash
  refine Hash do
    def initialize(*args)
      super
      # something here
    end

    def [](key)
      'whatever'
    end
  end
end

class Hello
  using RefinedHash

  def initialize
    h = Hash.new
    p h[:test]
  end
end

Hello.new # => "whatever"

As a result [] works well and returns 'whatever' for calls with any key (just for the test purposes to know that our refinement was effectively applied). But, alas, any code in refined initialize method won't be executed at all when I instantiate my Hash with the Hash.new up there. Am I missing something or is it stated somewhere that initialize couldn't be refined as any other method?

1 Answers

I'm not sure why initialize doesn't work. It could be because Class#allocate invokes it in some way that bypasses the refinement mechanism? But you can refine new, for the same effect:

module RefinedHash
  refine Hash.singleton_class do
    def new(*args)
      obj = super
      # something here
      obj
    end
  end
end
Related