Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to limit the number of location with rubygeocoder gem?

I have a location object so location.nearbys get all the locations near location. But I want to limit the results to 5. That I am doing with location.nearbys.limit(5) , but the problem is when there are no nearby location I get an error message . It says limit cant be used on empty array []. So, what's the solution. I can use.

location = location.nearbys
location = location.nearbys.limit(5) unless location.empty?

Do I have better ways to do this ? I am using mongoid , rails 3.0.7 , ruby 1.9.2 .

like image 381
Prabesh Shrestha Avatar asked Dec 27 '22 16:12

Prabesh Shrestha


1 Answers

The problem is that rubygeocoder returns a ActiveRecord::Relation if successful, but an empty Array on failure. And Ruby's Array does not respond to limit, so my tip is to use first(number) instead of limit(number), which will work with both results.


Found out, that the best solution of this problem is to use take(5) which will work both on Mongoid::Criteria objects and Ruby Arrays.

like image 170
Mario Uher Avatar answered Mar 15 '23 01:03

Mario Uher