0

I have a third-party code that's like this:

class Foo
  def initialize
    @hello = "world"
  end

  def msg
    @hello
  end
end

Then, I added a new file foo_redefinition.rb with these contents

class Foo
  def initialize
    @hello = "welt"
  end
end

Then, another third party code calls a method in my main class, and in the file of my main class I do require_relative 'foo_redefinition'. However, when the third party code (after calling my method, thus reading my main file, which requires the redefinition) calls Foo.msg, it returns "world", not "welt".

Also, when I do

require_relative 'foo_redefinition'

# ... lots of code

Foo::new.msg #=> world (instead of welt)

My questions are:

  1. Is it possible to redefine an initialize method?
  2. If so, what I am doing wrong here?
Luís Guilherme
  • 2,620
  • 6
  • 26
  • 41
  • 1
    `initialize` is a method just like any other method. There is absolutely nothing special whatsoever about it. So, your question is: can I redefine methods? And the answer is: yes. The answer to your second question is: I don't know. There's not enough information in your post. – Jörg W Mittag Aug 09 '16 at 21:09
  • I assume thus I am redefining initialize after the instance I wished to alter (and to which I have no access whatsoever) has already been initialized, so the change occurs, but to no effect. – Luís Guilherme Aug 09 '16 at 21:14
  • Answers to your questions are 1) yes; 2) I have no idea without seeing a full example which works the way you describe. – Chad S. Aug 09 '16 at 22:15

1 Answers1

2

I'm afraid that Foo is a lazily autoloaded class, and you are "redefining" initialize before Foo is loaded.

Try this

Foo.class_eval do
  def initialize
    @hello = "welt"
  end
end

This forces Foo to be loaded before redefining anything.

Aetherus
  • 8,720
  • 1
  • 22
  • 36