不寻常地使用模块命名空间

时间:2014-12-31 04:26:36

标签: ruby namespaces

我熟悉模块,它允许类访问模块中包含的实例方法,但是我没有看到模块允许类访问局部变量。

这是文件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

为什么文件A可以访问本地变量DB?模块中的任何内容都在同一名称空间中,甚至跨文件吗?

2 个答案:

答案 0 :(得分:1)

  

为什么文件A可以访问本地变量DB

因为它不是局部变量。局部变量以小写字母开头。它是一个常量,因为它以大写字母开头。

在当前作用域和所有封闭作用域(例如,类似于嵌套块中的局部变量)中以及在当前类或模块及其所有超类中动态查找常量。

答案 1 :(得分:0)

DB是模块级常量。这就是为什么它可以在两个文件中访问。

相关问题