In my Rails app I want to validate the filter and post_type params.
Both are optional, but if they are present they must have a value and must have a value that matches one in an array of valid values.
In my controller I have two methods for checking them:
def validate_filter
if params.has_key?(:filter)
if params[:filter].present?
if ['popular', 'following', 'picks', 'promoted', 'first-posts'].include?(params[:filter])
return true
else
return false
end
else
return false
end
else
return true
end
end
def validate_post_type
if params.has_key?(:post_type)
if params[:post_type].present?
if ['discussions', 'snaps', 'code', 'links'].include?(params[:post_type])
return true
else
return false
end
else
return false
end
else
return true
end
end
And then in my main controller method I do:
def index
raise ActionController::RoutingError.new('Not Found') unless validate_filter && validate_post_type
...
So this means post_type= and post_type=cam would return a 404 but post_type=snaps would return true.
Is there a better way to validate that the params passed are valid but for both empty and if the key itself exists. Using just blank? and present? is not enough in this scenario.
dry-validationis great for this sort of thing: dry-rb.org/gems/dry-validation/1.8