Josh Hepworth

What Class Methods Say
Communicating With Code

In Ruby, we have class methods (or module methods) in our toolbox. This allows us to communicate behavior and properties of groups of objects, instead of the behavior of just one object.

For example, suppose we have a chair:

class Chair
  attr_reader :material, :has_back, :build_date
end

We can use class methods to communicate possible values different objects of the Chair type can have. This gives others clarity about the limits of the system, and what assumptions you made when you first wrote the class.

class Chair
  def self.available_materials
    [:wood, :metal, :plastic]
  end
end

We can also use class methods to group and collect objects of the Chair type. This pattern is also used by ActiveRecord via the scope method, which lets us find objects with certain properties.

class Chair
  def self.mid_century_modern_chairs
    @chairs.select { |chair|
      1945 < chair.build_date.year && 
        chair.build_date.year < 1965
    }
  end
end

Clarity surrounding the assumptions, limits, requirements, and common groupings in our applications effectively allow other developers to build a better understanding of the system as a whole. Use class methods to better communicate these attributes of your application, and think about what a class method might be trying to tell you about a group of objects the next time you encounter one!