Skip to content

Instantly share code, notes, and snippets.

@sowenjub
Forked from apneadiving/base.rb
Last active August 29, 2015 14:14
Show Gist options
  • Save sowenjub/854fad09ef0daabc1b5e to your computer and use it in GitHub Desktop.
Save sowenjub/854fad09ef0daabc1b5e to your computer and use it in GitHub Desktop.
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