What is this double-colon ::
? E.g. Foo::Bar
.
I found a definition:
The
::
is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module.
What good is scope (private, protected) if you can just use ::
to expose anything?
Ruby on rails uses :: for namespace resolution.
To use it :
Also, other usage is : When using nested routes
OmniauthCallbacksController
is defined under users.and route is like :
No, it is not to access every method, it is a "resolution" operator, that is, you use it to resolve the scope (or location you can say) of a constant/static symbol.
For example in the first of your line, Rails use it to find the Base class inside the ActiveRecord.Module, in your second one it is used to locate the class method (static) of the Routes class, etc, etc.
It is not used to expose anything, its used to "locate" stuff around your scopes.
http://en.wikipedia.org/wiki/Scope_resolution_operator
::
is basically a namespace resolution operator. It allows you to access items in modules, or class-level items in classes. For example, say you had this setup:You could access
CONSTANT
from outside the module asSomeModule::InnerModule::MyClass::CONSTANT
.It doesn't affect instance methods defined on a class, since you access those with a different syntax (the dot
.
).Relevant note: If you want to go back to the top-level namespace, do this: ::SomeModule – Benjamin Oakes
Adding to previous answers, it is valid Ruby to use
::
to access instance methods. All the following are valid:As per best practices I believe only the last one is recommended.
This simple example illustrates it:
Taken from http://www.tutorialspoint.com/ruby/ruby_operators.htm
:: Is used to create a scope . In order to access Constant EATER from 2 modules we need to scope the modules to reach up to the constant