-
-
Save drhenner/8462170 to your computer and use it in GitHub Desktop.
# The purpose of this gist is to propose use of inheritance when upgrading objects to have "more functionality". | |
# For example: | |
# Lets say you have a `company` model and your project manager purposes a huge pivot to your existing application. | |
# Now new fields are "required" for the new companies you create. Unfortunately adding validators to the existing | |
# `company` model will cause things to blow up. You could create a form object for the new forms with form specific | |
# validators. Several issues are now introduced: | |
# 1) There can be several form objects for the company. Each with a slight difference in logic. | |
# 2) Any time you change something with the company model, every form object needs to be looked at. | |
# Instead you can simply create a new object that inherits from Company... | |
class FirmCompany < Company | |
end | |
# Now the new validators can be added to the `FirmCompany` object. The goal would be to move all the validators to the | |
# original `Company` object once the old data is cleaned up. In the mean time the application will not blow up while | |
# the old data is being sanitized. |
+1
yep
Have you considered the other way pivot, when you need to disable a validation rule?
also, why is #1 an issue? squashing different behaviors into one class increases the complexity of code, so it's always better to have a few small robust classes than one huge 500-line and 100-method monster.
One more use case: validating nested associations
class Company
has_one :address
validates_nested_attributes_for :address
end
class Address
end
Let's say there is a form where you need to add validates :foo
to Address
not breaking legacy code where this field is not required.
Subclassing both Company
and Address
for this purpose would be too much, right?
Actually, a lot of people in Rails community are using form objects, so maybe it is not that bad?
http://railscasts.com/episodes/416-form-objects
https://medium.com/p/84b6849c886e
http://nicksda.apotomo.de/2013/05/reform-decouple-your-forms-from-your-models/
http://robots.thoughtbot.com/activemodel-form-objects
http://rhnh.net/2012/12/03/form-objects-in-rails
And a few thoughts about inheritance in general: http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance
i definitely agree there is a time and place for form objects. i think the problem here was it made the code more complex by repeating validations and logic for simple CRUD actions that had no side effects (unlike something akin to user registration which may trigger notifications, etc.)
+1