Module: Lev::HandleWith
- Defined in:
- lib/lev/handle_with.rb
Overview
A utility method for calling handlers from controllers. To use, include this in your relevant controllers (or in your ApplicationController), e.g.:
class ApplicationController
include Lev::HandleWith
...
end
Then, call it from your various controller actions, e.g.:
handle_with(MyFormHandler,
params: params,
success: lambda { redirect_to 'show', notice: 'Success!'},
failure: lambda { render 'new', alert: 'Error' })
handle_with takes care of calling the handler and populates The ‘success’ and ‘failure’ lambdas are called if there aren’t or are errors, respectively. Alternatively, if you supply a ‘complete’ lambda, that lambda will be called regardless of whether there are any errors.
Specifying ‘params’ is optional. If you don’t specify it, HandleWith will use the entire params hash from the request.
Instance Method Summary collapse
Instance Method Details
#handle_with(handler, options) ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/lev/handle_with.rb', line 31 def handle_with(handler, ) success_action = .delete(:success) || lambda {} failure_action = .delete(:failure) || lambda {} complete_action = .delete(:complete) || lambda {} [:params] ||= params [:request] ||= request [:caller] ||= current_user @results, @errors = handler.handle() if complete_action.nil? @errors.empty? ? success_action.call : failure_action.call else complete_action.call end end |