What does :: do?

前端 未结 5 1684
南旧
南旧 2020-12-16 23:18

I have some inherited code that I am modifying. However, I am seeing something strange(to me).

I see some code like this:

::User.find_by_email(params         


        
相关标签:
5条回答
  • 2020-12-16 23:46

    :: is a scope resolution operator, it effectively means "in the namespace", so ActiveRecord::Base means "Base, in the namespace of ActiveRecord"

    A constant being resolved outside of any namespace means exactly what it sounds like - a constant not in any namespace at all.

    It's used in places where code may be ambiguous without it:

    module Document
      class Table # Represents a data table
    
        def setup
          Table # Refers to the Document::Table class
          ::Table # Refers to the furniture class
        end
    
      end
    end
    
    class Table # Represents furniture
    end
    
    0 讨论(0)
  • 2020-12-16 23:51

    Ruby uses (among other things) lexical scoping to find constant names. For example, if you have this code:

    module Foo
      class Bar
      end
    
      def self.get_bar
        Bar.new
      end
    end
    
    class Bar
    end
    

    The Foo.get_bar returns an instance of Foo::Bar. But if we put :: in front of a constant name, it forces Ruby to only look in the top level for the constant. So ::Bar always refers the top-level Bar class.

    You will run into situations in Ruby where the way your code is being run will force you to use these 'absolute' constant references to get to the class you want.

    0 讨论(0)
  • 2020-12-16 23:53

    You might find a lead here: What is Ruby's double-colon `::`?

    0 讨论(0)
  • 2020-12-16 23:58

    The "::" operator is used to access Classes inside modules. That way you can also indirectly access methods. Example:

    module Mathematics
        class Adder
           def Adder.add(operand_one, operand_two)
               return operand_one + operand_two
           end
        end
    end
    

    You access this way:

    puts “2 + 3 = “ + Mathematics::Adder.add(2, 3).to_s
    
    0 讨论(0)
  • 2020-12-17 00:02

    It makes sure to load the User model in the global namespace.

    Imagine you have a global User model and another User model in your current module (Foo::User). By Calling ::User you make sure to get the global one.

    0 讨论(0)
提交回复
热议问题