Object Composition Live-Code
Learning Goals
- Have concrete examples and strategies of Ruby syntax that model one-to-one relationships
- Have concrete examples and strategies of Ruby syntax that model one-to-many relationships
What's in this Repo
main.rb
- This is a file that loads all of the other files. It contains recommended comments and
puts
statements about what to cover and how, though instructors should feel empowered to use or change whatever feels most appropriate
- This is a file that loads all of the other files. It contains recommended comments and
order.rb
- Defines the class
Order
with the attributesid
andshipment
- Defines the class
shipment.rb
- Defines the class
Shipment
with the attributestracking_number
- Defines the class
merchant.rb
- Defines the class
Merchant
with the attributesname
andproducts
- Defines the class
product.rb
- Defines the class
Product
with the attributename
- Defines the class
Instructors
You should be modifying your code on a new branch that is your class name, ie leaves
, branches
, sockets
, ports
, etc.
One to One Relationships
One to one relationships should be tracked using instance variables, named appropriately and singular, and assigning values to them.
To summarize:
- To read one-to-one relationships, we read instance variables using the dot syntax
- To set one-to-one relationships, we should be assigning values to instance variables
Demo
Run through the first comment section in main.rb
.
Questions for during or after the Demo
Note the attr_accessor
in the Order
class. What attribute is attached to attr_accessor
? Why couldn't it be attr_reader
?
Optional: What alternative syntax could we use?
One to Many Relationships
One to many relationships should be tracked using instance variables, named appropriately and plural, and creating an empty array and modifying the array.
To summarize:
- To read one-to-many relationships, we read instance variables using the dot syntax and get back an array
- To set one-to-one relationships, we should be assigning values to instance variables, or pushing/modifying existing instance variables
Demo
Questions for during or after the Demo
Note the attr_reader
in the Merchant
class. What attributes are attached to attr_reader
? Why do we not need attr_accessor
?