Beware of Ruby namespaces

Posted by Paolo Fri, 17 Aug 2007 20:02:00 GMT

X=100

module A 
  module B
    X=200
  end
end

# ------- Case 1 ------------
module A
  module B
    class C
      p X
      p self.class.nesting
    end
  end
end

# this produces:
# 200
#[A::B::C, A::B, A]

# ------- Case 2 ------------
class A::B::C
  p X
  p self.class.nesting
end

# this produces:
# 100
#[A::B::C]

This post is basically a note to myself: the :: notation in Ruby is NOT a shortcut for nesting modules. In the second case class C is not able to see the X constant inside B (and shows the value of the outer one).

Socialize it: Add to del.icio.us Digg it! Technorati: Beware of Ruby namespaces Add to reddit.com

Posted in  | Tags , , ,  | no comments | no trackbacks


SeeSaw srl - Via Monte Pasubio, 8 37126 Verona - tel +39 045 4857457 fax 045 4851151 P.Iva 03609790237