March 2025
Intermediate to advanced
472 pages
12h 10m
English
Ruby has two basic concepts for organizing methods: classes and modules. We cover each in turn.
Here’s a Ruby class definition:
| 1: | class Order < ActiveRecord::Base |
| - | has_many :line_items |
| - | def self.find_all_unpaid |
| - | self.where("paid = 0") |
| 5: | end |
| - | def total |
| - | sum = 0 |
| - | line_items.each {|li| sum += li.total} |
| - | sum |
| 10: | end |
| - | end |
Class definitions start with the class keyword and are followed by the class name (which must start with an uppercase letter). This Order class is defined to be a subclass of the ApplicationRecord class.
Rails makes heavy use of class-level declarations. Here, has_many is a method that’s defined by Active Record. It’s called as the Order class is being ...
Read now
Unlock full access