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.
- 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)
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.
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.