Skip to content

Instantly share code, notes, and snippets.

@evanleck
Created Dec 8, 2015
Embed
What would you like to do?
Simple Strong Parameters in Sinatra
#
# A way to require parameters
#
# get '/', needs: [:id, :action] do
# erb :index
# end
#
# Does not modify the parameters available to the request scope.
# Raises a RequiredParamMissing error if a needed param is missing
#
app.set(:needs) do |*needed|
condition do
if @params.nil? || @params.empty? && !needed.empty?
fail RequiredParamMissing, settings.missing_parameter_message
else
needed = needed.map(&:to_sym) # make sure it's a symbol
sym_params = @params.dup
# symbolize the keys so we know what we're looking at
sym_params.keys.each do |key|
sym_params[(key.to_sym rescue key) || key] = sym_params.delete(key)
end
if needed.any? { |key| sym_params[key].nil? || sym_params[key].empty? }
fail RequiredParamMissing, settings.missing_parameter_message
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment