Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

4 | Chapter 1: Foundational Techniques


This concept is extremely useful in ActiveRecord. After creating your basic schema
and model objects, you can begin to build abstractions on top of those objects. Many
Rails projects start out by building abstractions on the model like this, before writ-
ing a single line of controller code or even designing the web interface:


class Order < ActiveRecord::Base
has_many :line_items

def total
subtotal + shipping + tax
end

def subtotal
line_items.sum(:price)
end

def shipping
shipping_base_price + line_items.sum(:shipping)
end

def tax
subtotal * TAX_RATE
end
end

Ruby Foundations


This book relies heavily on a firm understanding of Ruby. This section will
explain some aspects of Ruby that are often confusing or misunderstood. Some of
this may be familiar, but these are important concepts that form the basis for the
metaprogramming techniques covered later in this chapter.


Classes and Modules


Classes and modules are the foundation of object-oriented programming in Ruby.
Classes facilitate encapsulation and separation of concerns. Modules can be used as
mixins—bundles of functionality that are added onto a class to add behaviors in lieu
of multiple inheritance. Modules are also used to separate classes into namespaces.


In Ruby, every class name is a constant. This is why Ruby requires class names to
begin with an uppercase letter. The constant evaluates to theclass object, which is an
object of the classClass. This is distinct from theClass object, which represents the
actual classClass.*When we refer to a “class object” (with a lowercase C), we mean
any object that represents a class (includingClassitself). When we refer to the “Class
object” (uppercase C), we mean the classClass, which is the superclass of all class
objects.



  • If that weren’t confusing enough, theClass object has classClass as well.

Free download pdf