Best Practices for Class Methods

Class Method Basics

Class methods are a tool in ruby whereby you are operating on a class rather than an instance of a class. It is called on using the Class.Method notation rather than the Instance.Method notation.

Common Uses

  • Returning a saved class variable (i.e., @@all)
  • Manipulating data from within a class (i.e., self.count to iterate over and count unique values within a class)
  • Exporting to external source (i.e., create/drop table in SQL)
  • Importing from external source (i.e., creating instances from SQL query)
Active Records library of class methods

Where do class methods come from?

Class methods can be defined within a class by using notation of def self.method_name. The self in this case is referring to the Class that you are inside of.

A class can also receive a class method through extend. This is done by writing extend ModuleA within the code block of the class. All the methods that are within that module will become class methods.

Class methods may also be inherited from a super, or parent class. This is done through the inheritance operator of ClassA < ClassB, where ClassA is inheriting ClassB’s methods.

What does the above code return?
When you combine class inheritance AND module extension. Note: A module extension overrides a class inheritance with the same method name.

In summary, class methods are a useful tool to help keep track of, or create data. They can come from many sources, therefore we have to be careful on what we send them through modules or parent classes. Best practice for now might be to declare class methods within the actual class to prevent unexpected behavior through overriding.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.