February 14, 2016

Does your API support pagination for certain resources? If so, you might be writing code like this

#...
def index
  page = params.fetch(:page, 1)
  per_page = params.fetch(:per_page, 10)
  #...
end

The problem with this is that anyone can abuse your endpoint by sending per_page=9999999999 and you might end up paying a bit extra for bandwidth, so to help lower your bills, write something like this

def clamp(min_value, max_value, inputted_value)
  [min_value, max_value, inputted_value].sort[1]
end

# ...

def index
  page = clamp(1, Resource.total_pages, params.fetch(:page, 1))
  per_page = clamp(1, 10, params.fetch(:per_page, 10))
  #...
end 

Update: alternatively, if using kaminari, you can set a max_per_page in the configuration options.

blog comments powered by Disqus