Skip to content

Instantly share code, notes, and snippets.

@latortuga
Created May 4, 2015 23:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save latortuga/5e698ffd9f75accdf6a8 to your computer and use it in GitHub Desktop.
Save latortuga/5e698ffd9f75accdf6a8 to your computer and use it in GitHub Desktop.
# 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
# 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