Last Updated: February 25, 2016
·
235
· pniemczyk

Simple way for separate validation from domain model

Fat model with validation on all cases always causes problems in the future. So my solution is ShadowForm. Now you can have your original model without validation and use forms when you need specific validation. This works with ActiveRecord and ActiveModel as well.

How it works

You have your activerecord or activemodel model:
ruby class User include ActiveModel::Model attr_accessor :name, :email, :password end
And for example register form
ruby class UserRegistrationForm < ShadowForm shadow_of User validation do validates :email, presence: true validates :password, presence: true end end
And now you have UserRegistrationForm like User + Validation

If you need form for email update you simple create new one like this:

class UserEmailUpdateForm < ShadowForm
  shadow_of User
  validation do
    validates :email, presence: true
  end
end

Check on :