Created
December 27, 2011 20:40
-
-
Save ajsharp/1525057 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # This class is responsible API parameter type coercion and defaults. | |
| class ListingSearchParam | |
| APPROVED = [:query, :latlng, :box, :sort, :limit, :page, :category_ids, :fulfilled] | |
| def self.parse(opts = {}) | |
| new(opts).parse | |
| end | |
| def initialize(opts = {}) | |
| @errors = ActiveModel::Errors.new(self) | |
| @opts = opts.slice(*APPROVED) | |
| @opts[:distance] = (@opts[:distance] || 100).to_i | |
| @opts[:limit] = (@opts[:limit] || 100).to_i | |
| @opts[:query] = @opts[:query].downcase | |
| errors.add(:base, "Cannot sort by distance without latlng parameter") if @opts['sort'] == 'distance' && !@opts['latlng'] | |
| if @opts[:box] | |
| begin | |
| @opts[:box] = @box[:box].split(',').map{ |k| Float(k) } | |
| rescue | |
| errors.add(:base, "Invalid bounding box string sent") | |
| end | |
| errors.add(:base, "Invalid bounding box string sent") unless @opts['box'].present? && @opts['box'].size == 4 | |
| @opts['box'] = @opts['box'].in_groups_of(2) | |
| end | |
| if @opts['latlng'] | |
| begin | |
| # @todo wrap this up somehow. Maybe in a LatLng class | |
| latlng = @opts['latlng'] = @opts['latlng'].split(',').map{|k|Float(k).round(6)} | |
| rescue | |
| errors.add(:base, "Invalid lat/lng string sent") | |
| end | |
| errors.add(:base, "Invalid lat/lng string sent") unless latlng.present? && latlng.size == 2 | |
| end | |
| end | |
| def parse | |
| @opts | |
| end | |
| # last three methods required for ActiveModel::Errors | |
| def validate! | |
| end | |
| def read_attribute_for_validation(attr) | |
| @opts[attr] | |
| end | |
| def self.human_attribute_name(attr, options = {}) | |
| attr | |
| end | |
| def self.lookup_ancestors | |
| [self] | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment