Organizing Structures
Get familiar with Ruby's classes and modules
Ruby has two basic concepts for organizing methods: classes and modules. We will cover each in turn.
Classes
Here’s a Ruby class definition:
Press + to interact
class Order < ApplicationRecordhas_many :line_itemsdef self.find_all_unpaidself.where('paid = 0')enddef totalsum = 0line_items.each {|li| sum += li.total}sumendend
Class definitions start with the class keyword, followed by the class name (which must start with an uppercase letter). This Order
class is defined as a subclass of the ApplicationRecord
class.
Rails makes heavy use of class-level declarations. Here, has_many
in line 2 is a method that’s defined by Active Record. It’s called “The definition of Order class”. Normally these kinds of methods make assertions about the class, so in this course we ...