patrick
patrick

Reputation: 9752

is there a more elegant way to write this in ruby?

class Geolocation < ActiveRecord::Base
  scope :lat_greater_than_or_equal_to, lambda { |lat| where("latitude >= ?", lat) }
  scope :lat_less_than_or_equal_to,    lambda { |lat| where("latitude <= ?", lat) }
  scope :lng_greater_than_or_equal_to, lambda { |lng| where("longitude >= ?", lng) }
  scope :lng_less_than_or_equal_to,    lambda { |lng| where("longitude <= ?", lng) }
end

So with this, I am doing:

Geolocation.lat_greater_than_or_equal_to(lat_min).
            lat_less_than_or_equal_to(lat_max).
            lng_greater_than_or_equal_to(lng_min).
            lng_less_than_or_equal_to(lng_max)

Not that this is horrible, but I was wondering if there's a nicer way?

Upvotes: 0

Views: 84

Answers (1)

rubish
rubish

Reputation: 10907

Effectively what you want is a binding box, which needs four corners. So other way to write it can be:

class Geolocation < ActiveRecord::Base
  scope :binding_box, lambda { |lat_min, lng_max, lat_max, lng_min| where(
      "latitude >= ? AND latitude <= ? AND longitude >= ? AND longitude <= ?", 
      lat_min, lat_max, lng_min, lng_max
  )}
end

Geolocation.binding_box(lat_min, lng_max, lat_max, lng_min)

Upvotes: 3

Related Questions