-1

In ruby I read that a class cannot inherit from multiple classes but in rails there is this code:

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
end

inside app/models/application_record.rb

I know about symbols in ruby but what does this ActiveRecord::Base mean in the rails application file? I want to know

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367

1 Answers1

3

It's just a namespace separator, as in:

module Example
  class Name
  end
end

That's Example::Name.

It's also used to reference a top-level namespace to avoid ambiguity, as in:

module Name
  class Example
  end
end

module Example
  class Name
    def initialize
      @example = ::Name::Example.new
    end
  end
end

Where :: at the start means "from the top", as opposed to the closest possible match, which in this case would be Example::Name.

tadman
  • 208,517
  • 23
  • 234
  • 262
  • Is it the same as saying `Example.Name` when you intend to include the Name class from the Example module – omokehinde igbekoyi Oct 26 '20 at 18:48
  • 1
    The `.` part means "method call" and there is no method named `Name` here, so that's not equivalent. Where `.` is shorthand for `.send(...)`, as in `X.y` is `X.send(:y)`, the `::` is more like `X::Y` is the same as `X.const_get(:Y)`. – tadman Oct 26 '20 at 18:55
  • 1
    This is why if you had `module X; Y = :value; end` then `X::Y` gets you that constant. Remember clases and modules are just constants by virtue of having a capitalized first letter, what Ruby uses to signify that. – tadman Oct 26 '20 at 18:56
  • 1
    On occasion you'll see `X::y` and `X.y` used interchangeably for *class methods*, but I prefer the second form to make it clear it's a method call. In Ruby you don't need to make this explicit, `X::y` does seem ambiguous, whereas `X::y()` makes it clear, but cluttered. `X.y` leaves no confusion as to what's going on. – tadman Oct 26 '20 at 18:58
  • Thanks! what about this method `belongs_to :player` in a rails class model. I think this is a method that takes a symbol as an argument, am I correct? If I am then how is this possible? if am not please explain better to me. – omokehinde igbekoyi Oct 27 '20 at 22:59
  • 1
    Methods can take whatever they want as arguments, symbols included. Note that `:x` is very different from `::X`. A symbol is just an "internalized string", or a short-hand string constant. All `:x` are equal, but `"x"` may not be the same object as some other `"x"`, making comparisons more expensive. This is why you see symbols used a lot. – tadman Oct 27 '20 at 23:08