Last active
August 15, 2019 17:38
-
-
Save StevenJL/1cfd383cfe66b3d4112e76a19b3e94f3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Account < ActiveRecord::Base | |
def withdraw(amount) | |
# ... | |
end | |
def deposit(amount) | |
# ... | |
end | |
def close! | |
update_attribute!(closed_at, Time.current) | |
end | |
end | |
# These three types of accounts inherit from a common base class | |
# so they can all share a common `#close` method. However, each | |
# class has its own class-specific methods. | |
class CorporateAccount < Account | |
def close! | |
inform_share_holders! | |
super | |
end | |
end | |
class SmallBusinessAccount < Account | |
def close! | |
inform_mom_and_pop! | |
super | |
end | |
end | |
class PersonalAccount < Account | |
def close! | |
inform_dude_or_dudette! | |
super | |
end | |
end | |
# Rails is smart enough to detect STI if we add a `type` column | |
# in the `accounts` table. | |
class CreateAccounts < ActiveRecord::Migration | |
def change | |
create_table :accounts do |t| | |
t.string :type | |
t.float :balance | |
t.string :tax_identifier | |
t.date_time :closed_at | |
# ... more column fields # | |
t.timestamps | |
end | |
end | |
end | |
# Creation of a corporate account will create a new record in the | |
# `accounts` table, but with `type` equal to "corporate". | |
CorporateAccount.create(name: "Evil Corp", tax_identifier: "6664201369" ...) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment