Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby "Base" classes

Tags:

ruby

It seems commonplace to name classes "Base" in Ruby. I'm not sure why, nor how I feel about it.

Consider, for example, ActiveRecord. ActiveRecord is a module that contains a number of classes such as Observer and Migration, as well as a class called Base. What's the benefit of this, as opposed to having an ActiveRecord class that contains Observer and Migration?

class ActiveRecord

  class Observer
    [...]
  end

  class Migration
    [...]
  end

end

vs

module ActiveRecord

  class Base
    [...]
  end

  class Observer
    [...]
  end

  class Migration
    [...]
  end

end
like image 262
Johannes Gorset Avatar asked Sep 21 '10 07:09

Johannes Gorset


People also ask

What is base class in Ruby?

The Base class is commonly used to identify an abstract class, intended to be extended and implemented in a concrete class by the developer. For instance, ActiveRecord::Base is the abstract class for any Active Record model in a Rails project. A model looks like class User < ActiveRecord::Base end.

What is a subclass in Ruby?

Sub class: This is the class that is derived from the parent class. It is also known as a subclass or derived class or child class. You can also add its own objects, methods, along with the base class methods and objects, etc. Note: By default, every class in Ruby has a Super class.

What are classes in Ruby?

What is a class in Ruby? Classes are the basic building blocks in Object-Oriented Programming (OOP) & they help you define a blueprint for creating objects. Objects are the products of the class.

What are the base classes?

What is a Base Class? In an object-oriented programming language, a base class is an existing class from which the other classes are determined and properties are inherited. It is also known as a superclass or parent class.


1 Answers

The Base class is commonly used to identify an abstract class, intended to be extended and implemented in a concrete class by the developer.

For instance, ActiveRecord::Base is the abstract class for any Active Record model in a Rails project. A model looks like

class User < ActiveRecord::Base
end

Likewise, Observer defines its own Observer::Base and Action Controller defines ActionController::Base which, in a Rails project, is immediately implemented by ApplicationController::Base.

Ruby doesn't provide and language-level keyword or syntax to define abstract classes. Technically speaking, ActiveRecord::Base it's not a real abstract class, but it's a kind of convention to use Base for this pattern.

like image 190
Simone Carletti Avatar answered Dec 31 '22 02:12

Simone Carletti