Created
October 2, 2017 17:09
-
-
Save zernie/c37d24fab63fe2e4d9c76feab3964983 to your computer and use it in GitHub Desktop.
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
module FormObjectHelpers | |
extend ActiveSupport::Concern | |
included do | |
def form(klass, attributes = {}, options = {}) | |
form = klass.new(current_user, params, attributes) | |
authorize_model(form, options) | |
yield form if block_given? | |
render action_name, locals: { form: form } | |
end | |
def run(klass, attributes = {}, options = {}) | |
form = klass.new(current_user, params, attributes) | |
authorize_model(form, options) | |
yield form if block_given? | |
call_form(form, options) | |
end | |
private | |
def authorize_model(form, options = {}) | |
authorize form.model if options.fetch(:authorize, true) | |
end | |
def call_form(form, options) | |
on_success, on_fail, after_success, after_fail = extract_callbacks(options) | |
if form.valid? | |
form.call | |
on_success.(form.model, form) | |
after_success.(form.model, form) | |
else | |
on_fail.(form.model, form) | |
after_fail.(form.model, form) | |
end | |
end | |
def extract_callbacks(options = {}) | |
[ | |
options.fetch(:on_success, -> (model, _) { respond_with model, options.slice(:notice, :status) }), | |
options.fetch(:on_fail, -> (model, _) { respond_with model, options.slice(:alert, :status) }), | |
options.fetch(:after_success, -> (*) {}), | |
options.fetch(:after_fail, -> (*) {}) | |
] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment