0

Is it there a way to define a module callback similar to Module#included, but to be called after the receiver's definition is over ?

For example, in order to be able to access receiver's methods defined after the inclusion :

module A
  def self.included(base)

    if base.respond_to? :foo
      puts ":foo is defined in #{base}"
    else
      puts ":foo is not defined in #{base}"
    end

  end
end

class B
  include A

  def self.foo ; end
end

# :foo is not defined in B

It is possible to include the module at the end of the receiver's definition, but it feels less idiomatic :

class C
  def self.foo ; end

  include A
end
# :foo is defined in C
MrRuru
  • 1,932
  • 2
  • 20
  • 24
  • The main difference (the only one?) is that if the class mixes in a method from the module that is also in the class, the module's method will overwrite class `C`'s method and be overwritten by class `B`'s method. – Cary Swoveland Feb 26 '15 at 22:08
  • Yes, but is there a way to circumvent this behavior? Like, an `after_defined` hook called by the B when it reaches the end of the class definition. – MrRuru Feb 26 '15 at 22:27
  • It doesn't seem like there's a cleaner way than writing the include at the end. Do you need access to the class's definitions in the `included` hook, or are you just wanting the module methods to take priority over the class's methods? If it's the latter, you could try `prepend`: http://stackoverflow.com/a/15384720/4280232 – alexcavalli Feb 26 '15 at 23:07
  • I don't know if it would buy you anything, but you could write `class B; end; B.include A`. – Cary Swoveland Feb 27 '15 at 00:17

0 Answers0