Jwan622
Jwan622

Reputation: 11649

Unusual use of module namespacing

I am familiar with modules giving a class access to instance methods included in the module, but I have not seen modules giving classes access to local variables.

Here is file 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

Here is file B:

module SequelPlayground
  DB = Sequel.postgres("sequel-playground")

  class Server < Sinatra::Base
    get '/' do
      erb :index
    end
  end
end

Why does file A have access to the local variable DB? Are anything within a module in the same namespace even across files?

Upvotes: 2

Views: 59

Answers (2)

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369458

Why does file A have access to the local variable DB?

Because it's not a local variable. Local variables start with lowercase letters. It's a constant, because it starts with an uppercase letter.

Constants are looked up both lexically in the current scope and all enclosing scopes (similar to local variables in nested blocks, for example) and dynamically in the current class or module and all its superclasses.

Upvotes: 1

prashant
prashant

Reputation: 108

DB is a module level constant. that is why it is accessible in both the files.

Upvotes: 0

Related Questions