This is a common pattern in Rails, so common that there is a Ruby Objct extension for it called presence
.
Returns the receiver if it's present otherwise returns nil. object.presence is equivalent to
object.present? ? object : nil
In your case, the code will be changed from
dump = params[:dump] ? params[:dump] : 'false'
to
dump = params[:dump].presence || false
It's hard to refactor the entire code, because it's not clear what should happen in case the parameter is false. I assume you may want to display an error.
If that's the case, there is also another way: use an exception, or even better, reuse require
from the Rails strong parameters feature, which is based on exceptions
dump = params.require(:dump)
This line alone, will allow you to get rid of the entire body.
def report
dump = params.require(:dump)
data = {}
render :json => p(data)
end
If the parameter is missing, an exception ActionController::ParameterMissing
is raised. You can rescue it in the app, and show the proper message.
rescue_from ActionController::ParameterMissing, with: :handle_parameter_missing
def handle_parameter_missing(exception)
# do what you want
end
false
. – 200_success♦ Nov 11 '14 at 21:34:)
– sircapsalot Nov 11 '14 at 21:36