Skip to content

Instantly share code, notes, and snippets.

@apneadiving
Last active August 29, 2015 14:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save apneadiving/c598bb357ec0a36ed5d9 to your computer and use it in GitHub Desktop.
Save apneadiving/c598bb357ec0a36ed5d9 to your computer and use it in GitHub Desktop.
form objects
class FormObjectBase
include ::ActiveModel::Validations
attr_reader :object, :params
def initialize(object)
@object = object
end
def assign(params)
raise 'implement it and return self'
self
end
def validate
if valid?
if object.valid?
true
else
inherit_errors
false
end
else
false
end
end
def submit(options = { validate: true })
if !options[:validate] || validate
save
else
false
end
end
private
def save
if object.save
true
else
delegate_errors
false
end
end
# take errors in the model directly
def inherit_errors
object.errors.each do |key, value|
errors.add(key, value)
end
end
end
form_object = ::WordersAdmin::FormObjects::User.new(user)
if form_object.assign(params.permit!).submit # its filtered in the form object, so no pb
class UserSignup < ::FormObjectBase
FIELDS = [
:email, :first_name, :last_name
]
validates :first_name, presence: true
validates :last_name, presence: true
def assign(params)
@params = params
object.attributes = params.slice *FIELDS
self
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment