Skip to content

Instantly share code, notes, and snippets.

@zernie
Created October 2, 2017 17:09
Show Gist options
  • Save zernie/c37d24fab63fe2e4d9c76feab3964983 to your computer and use it in GitHub Desktop.
Save zernie/c37d24fab63fe2e4d9c76feab3964983 to your computer and use it in GitHub Desktop.
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