[Rails] Rails namespace help requested

zdennis zdennis at mktec.com
Wed Dec 14 15:00:27 GMT 2005


Michael Engelhart wrote:
> Hi all -
> 
> I posted yesterday with the subject "namespace pollution" and with the
> high traffic on this list, it's kind of disappeared and I'm in need of
> a quick answer so i can move on.   To recap quickly, can someone tell
> if Rails is somehow forcing all modules into a single namespace?   I
> have a model class StateProvince and inside a webservice module in my
> lib/ directory I have a StateProvince as well but no matter what I do
> when running under Rails I get a superclass mismatch error.   This
> doesn't happen when I have standalone ruby code in similar situations.
> 

By default Rails classes are using toplevel namespace; ie: ActiveRecord, ActionController, 
ActionView, etc..

Rails also does not put your models into a separate namespace (though i wish it would =), and those 
also are toplevel. ie: User, Account, Session, Group, Article.

If you have any classes that you wrote that have the same names as your models or other toplevel 
classes/modules that Rails is using you need to either a) rename them or b) move them inside of 
another namespace.

The problem you are having is that the first time you define/open a class it has to define it's 
superclass.

class A ; end
class B < A; end

You cannot define/open a class and then later try to subclass it, ie:

class A; end
class B; end
class B < A; end # error!!

This is the scenario you're hitting with your namespace clash. Your StateProvince class is being 
initalized, then when it gets around to loading your StateProvince module it seems you're trying to 
define inheritance, and you can't do that now.

If you have namespace clashes but you are in your namespace you can use :: syntax to ensure you get 
the toplevel class/module. For example:

class StateProvince
end

module MyNameSpace
    class StateProvince
    end

    module MoreModules
       class MyStateProvinceModel < StateProvince
       end
    end
end

In the above code code your MyStateProvinceModel is going to subclass MyNameSpace::StateProvince 
because that is the first constant ruby finds while it is looking for "StateProvince". This may be 
wrong because your MyStateProvinceModel might need to subclass the toplevel StateProvince class. 
This is where the "::" comes in handy:

class StateProvince
end

module MyNameSpace
    class StateProvince
    end

    module MoreModules
       class MyStateProvinceModel < ::StateProvince
       end
    end
end

The leading :: on any constant will force ruby to look at the most toplevel constant.

I hope this helps more then it confuses,

Zach


More information about the Rails mailing list