Gristle McThornbody (craigp) wrote in ruby_lang,
Gristle McThornbody
craigp
ruby_lang

newbie question: dynamically extending class definitions in modules

I'm very confused by the behaviour of the following code (appended). The last two lines print "inner" and "outer" respectively. Why doesn't "class A::C" run in the context of A? Perhaps naively, it appears both quite surprising and that support for dynamically extending classes (defined within modules at least) is broken.

This appears to be expected behaviour. If so, why? Is it possible to dynamically update the definition of A::C so it would act as if it were originally defined within module A?

thanks!
--craig

CONST = "outer"

module A
  CONST = "inner" # This is A::CONST
end

module A
  class B
    def B.get_const
      CONST
    end
  end
  
  class C
  end
  
end

class A::C
def (A::C).get_const
CONST
end
end

puts A::B.get_const #inner
puts A::C.get_const #outer
  • Post a new comment

    Error

    default userpic
  • 3 comments