Ruby 模块名称空间的异常使用
我熟悉允许类访问模块中包含的实例方法的模块,但没有见过允许类访问局部变量的模块 这是文件Ruby 模块名称空间的异常使用,ruby,namespaces,Ruby,Namespaces,我熟悉允许类访问模块中包含的实例方法的模块,但没有见过允许类访问局部变量的模块 这是文件A: module SequelPlayground class Article attr_reader :title, :body, :author_id, :id def initialize(attributes) @title = attributes[:title] @body = attributes[:body]
A
:
module SequelPlayground
class Article
attr_reader :title, :body, :author_id, :id
def initialize(attributes)
@title = attributes[:title]
@body = attributes[:body]
@author_id = attributes[:author_id]
@id = attributes[:id]
end
def self.next_id
table.count + 1
end
def self.table
DB.from(:articles) #SELECT * FROM articles
end
end
end
这是文件B
:
module SequelPlayground
DB = Sequel.postgres("sequel-playground")
class Server < Sinatra::Base
get '/' do
erb :index
end
end
end
模块
DB=Sequel.postgres(“Sequel游乐场”)
类服务器
为什么文件
A
可以访问局部变量DB
?模块中的任何内容即使跨文件也在同一名称空间中吗?DB
是模块级常量。这就是为什么在两个文件中都可以访问它
为什么文件A
可以访问局部变量DB
因为它不是一个局部变量。局部变量以小写字母开头。它是一个常量,因为它以大写字母开头
常量在当前作用域和所有封闭作用域(例如,类似于嵌套块中的局部变量)中按词汇查找,在当前类或模块及其所有超类中动态查找。
DB
是模块级常量,而不是局部变量(按大写约定),我相信Ruby会解决它,在局部范围,然后向上搜索类、模块,直至全局范围。有趣的。。。我以前从来不知道。所以在文件A中,它在本地搜索DB,然后是模块,然后是全局搜索?是的-因为它以大写字母开头,Ruby假设它是一个常量,并在范围内向上搜索,直到找到它(或不找到它)