Running code after class is fully loaded

class A
  do_something_from_b

  def method_in_a
  end
end

module B
  def self.included base
    base.extend ClassMethods
  end

  module ClassMethods
    def do_something_from_b
      A.class_eval do
        alias_method :aliased_method_in_a, :method_in_a
      end
    end
  end
end

A.send(:include, B)

This code will not work, because when called do_somethind_from_b, method_in_adoes not exist yet.

So, is there a way to connect to class Aafter a full load, without placing the call do_something_from_bat the end class A?

Change . As stated, there are other things in the code, but it is not. I just want to illustrate what I want to execute, which runs some code after the class is closed (it doesn't matter that it can be reopened at will). And now I know that this is probably not possible.

Thanks!

+5
source share
1 answer

Ruby . , .

class A
  def method_in_a
  end
end

, , ( ).

class A
  alias :aliased_method_in_a :method_in_a
end

, ( , )

A.class_eval do
  alias :aliased_method_in_a :method_in_a
end

, A # method_in_a . , ,

require "file_of_class_a"

. , A # method_in_a,

class A
  def self.method_added(name)
    alias :aliased_method_in_a :method_in_a if name == :method_in_a
  end
end

A.method_added , A.

+5

All Articles