2

While browsing ActiveRecord source code I found :

class ActiveRecord::Base

I did not understand how a class name can be like ActiveRecord::Base Please explain it for me, I am not getting the concept.

4

1 に答える 1

5

ActiveRecord is actually a Ruby Module, which is originally defined similarly to:

module ActiveRecord
  # contents of module
end

Modules provide a namespace for classes and constants to be defined in, meaning classes can be defined inside modules, as ActiveRecord::Base is. So this is the same as

module ActiveRecord
  class Base
    # contents of class
  end
end

In general, the :: operator is used for namespace resolution, for referencing constants within namespaces. Technically, any variable beginning with a capital letter is a constant, so Base is a constant whose value is the class itself! And if there was a constant named FOO defined within ActiveRecord as follows:

module ActiveRecord
  FOO = "foo"
end

then its fully-qualified variable name would be ActiveRecord::FOO.

于 2013-03-27T06:33:22.737 に答える