Is there any difference between
module Foo class Engine < Rails::Engine end end
and
module Foo class Engine < ::Rails::Engine end end
operator is used to access the method of a class. Double colon operator. Double colon ( : ) operator is use to access the constants, class methods and instance methods defined within a class or module to anywhere outside the class or module.
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.
Ruby symbols are created by placing a colon (:) before a word. You can think of it as an immutable string. A symbol is an instance of Symbol class, and for any given name of symbol there is only one Symbol object.
The :: is a unary operator and is used to access (anywhere outside the class or module) constants, instance methods and class methods defined within a class or module. Note: In Ruby, classes and methods may be considered constants too.
Constants in Ruby are nested like files and directories in filesystem. So, constants are uniquely identified by their paths.
To draw an analogy with the file system:
::Rails::Engine #is an absolute path to the constant. # like /Rails/Engine in FS. Rails::Engine #is a path relative to the current tree level. # like ./Rails/Engine in FS.
Here is the illustration of possible error:
module Foo # We may not know about this in real big apps module Rails class Engine end end class Engine1 < Rails::Engine end class Engine2 < ::Rails::Engine end end Foo::Engine1.superclass => Foo::Rails::Engine # not what we want Foo::Engine2.superclass => Rails::Engine # correct
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With