Last active
August 29, 2015 14:10
-
-
Save apneadiving/c598bb357ec0a36ed5d9 to your computer and use it in GitHub Desktop.
form objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
form_object = ::WordersAdmin::FormObjects::User.new(user) | |
if form_object.assign(params.permit!).submit # its filtered in the form object, so no pb |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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