::做什么?

我有一些我正在修改的inheritance代码。 但是,我看到一些奇怪的东西(对我来说)。

我看到一些像这样的代码:

::User.find_by_email(params[:user][:email]).update_attributes(:mag => 1) 

我从未见过这样的东西(我是Ruby on Rails的新手)。 这是做什么的,为什么我的User.find_by_email(params[:user][:email]).update_attributes(:mag => 1)不起作用? 该错误说明了User常量。

如果有帮助,我正在使用Rails 2.3.5。

::是一个范围解析运算符,它实际上意味着“在命名空间中”,所以ActiveRecord::Base意味着“ Base ,在ActiveRecord的命名空间中”

在任何名称空间之外解析的常量意味着它听起来完全是什么 – 根本不在任何名称空间中的常量。

它用于代码可能不明确的地方:

 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 

它确保在全局命名空间中加载User模型。

想象一下,您的当前模块(Foo :: User)中有一个全局用户模型和另一个用户模型。 通过Calling :: User确保获得全局的。

你可能会在这里找到一个主角: 什么是Ruby的双冒号`::`?

Ruby使用(除其他外)词法范围来查找常量名称。 例如,如果您有此代码:

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

Foo.get_bar返回Foo::Bar的实例。 但是如果我们把::放在一个常量名称前面,它会迫使Ruby只查看常量的顶层。 所以::Bar总是引用顶级Bar类。

您将遇到Ruby中的情况,其中您的代码运行方式将强制您使用这些“绝对”常量引用来到达您想要的类。

“::”运算符用于访问模块内的类。 这样你也可以间接访问方法。 例:

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

你这样访问:

 puts “2 + 3 = “ + Mathematics::Adder.add(2, 3).to_s