Created
May 4, 2015 23:43
-
-
Save latortuga/5e698ffd9f75accdf6a8 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
# Imagine we have a form that only sets user name for verified users | |
class Form | |
include ActiveModel::Model | |
attr_accessor :name | |
def save(user) | |
user.name = name if user.verified? | |
end | |
end | |
# Now we want to make a new form that always sets user name, we have to reach into the superclass and copy its logic and introduce brittleness whenever the superclass logic changes. | |
class ApiForm < Form | |
def save(user) | |
# yuck, what if we add a new line of code to Form#save ? | |
user.name = name | |
end | |
end |
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
# Instead, implement your base class based on an abstraction: | |
class Form | |
include ActiveModel::Model | |
attr_accessor :name | |
def save(user) | |
if update_user_name? | |
user.name = name | |
end | |
end | |
private | |
def update_user_name? | |
user.verified? | |
end | |
end | |
# Simply override the template method from the base class | |
class ApiForm < Form | |
private | |
def update_user_name? | |
# awesome, no longer have to change every time Form#save changes | |
true | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment