Method defined in module doesn't have access to Constant in class it is imported into

Does anyone know why a method defined in a module that is then included in a
class does not have
access to the constants of that class? Doesn't including the module make
all its methods into instance methods
of the class? Shouldn't get_foo and class_get_foo in the following example
work the same?

module ModFoo
  def get_foo
     FOO
  end
end

class Foo
  FOO = 'this is foo'
  include ModFoo

  def class_get_foo
     FOO
  end
end

f = Foo.new
f.get_foo

f.get_foo

NameError: uninitialized constant ModFoo::FOO
        from (irb):3:in `get_foo'
        from (irb):11

f.class_get_foo
=> "this is foo"

···

from :0

Because Mod::FOO, and Foo::FOO are two different constants in two
different namespaces.

Included methods aren't source macros, they get compiled in the
context of the module that contains them, so when ModuleFoo#getFoo was
compiled, FOO got bound to ModuleFoo::FOO, hence the error.

···

On 4/9/07, Mike Sandler <mike.sandler@gmail.com> wrote:

Does anyone know why a method defined in a module that is then included in a
class does not have
access to the constants of that class? Doesn't including the module make
all its methods into instance methods
of the class? Shouldn't get_foo and class_get_foo in the following example
work the same?

module ModFoo
  def get_foo
     FOO
  end
end

class Foo
  FOO = 'this is foo'
  include ModFoo

  def class_get_foo
     FOO
  end
end

f = Foo.new
f.get_foo

>> f.get_foo
NameError: uninitialized constant ModFoo::FOO
        from (irb):3:in `get_foo'
        from (irb):11
        from :0

f.class_get_foo
=> "this is foo"

--
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

Mike Sandler wrote:

Does anyone know why a method defined in a module that is then included in a
class does not have
access to the constants of that class? Doesn't including the module make
all its methods into instance methods
of the class? Shouldn't get_foo and class_get_foo in the following example
work the same?

You can make it work as follows:

module ModFoo
def get_foo
    FOO

       self.class::FOO

···

end
end

--
        vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407