Skip to content

Instantly share code, notes, and snippets.

@thaichors3000
Created January 31, 2020 10:01
Show Gist options
  • Save thaichors3000/b7c77aa34de0f4ccd28a86b388a2de6c to your computer and use it in GitHub Desktop.
Save thaichors3000/b7c77aa34de0f4ccd28a86b388a2de6c to your computer and use it in GitHub Desktop.
Rails Service Design Patterns - Form Object - BaseForm
class BaseForm
include ActiveModel::Model
def persisted?
false
end
def save
return false unless valid?
persist!
true
rescue ActiveRecord::RecordInvalid
raise ActiveRecord::RecordInvalid, self
end
def save!
return true if save
raise ActiveRecord::RecordInvalid, self
end
private
def persist!; end
def delegate_validation_on(object, delegate_field, field = nil)
field ||= delegate_field
error = object.errors[delegate_field].first
errors.add(field, error) if error && !errors.added?(field, error)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment