]> git.openstreetmap.org Git - rails.git/blob - app/controllers/concerns/query_methods.rb
Move common query time condition to mixin
[rails.git] / app / controllers / concerns / query_methods.rb
1 module QueryMethods
2   extend ActiveSupport::Concern
3
4   private
5
6   ##
7   # Restrict the resulting items to those created during a particular time period
8   # Using 'to' requires specifying 'from' as well for historical reasons
9   def query_conditions_time(items, filter_property = :created_at)
10     interval = query_conditions_time_value
11
12     if interval
13       items.where(filter_property => interval)
14     else
15       items
16     end
17   end
18
19   ##
20   # Get query time interval from request parameters or nil
21   def query_conditions_time_value
22     if params[:from]
23       begin
24         from = Time.parse(params[:from]).utc
25       rescue ArgumentError
26         raise OSM::APIBadUserInput, "Date #{params[:from]} is in a wrong format"
27       end
28
29       begin
30         to = if params[:to]
31                Time.parse(params[:to]).utc
32              else
33                Time.now.utc
34              end
35       rescue ArgumentError
36         raise OSM::APIBadUserInput, "Date #{params[:to]} is in a wrong format"
37       end
38
39       from..to
40     end
41   end
42
43   ##
44   # Limit the result according to request parameters and settings
45   def query_limit(items)
46     items.limit(query_limit_value)
47   end
48
49   ##
50   # Get query limit value from request parameters and settings
51   def query_limit_value
52     name = controller_path.sub(%r{^api/}, "").tr("/", "_").singularize
53     max_limit = Settings["max_#{name}_query_limit"]
54     default_limit = Settings["default_#{name}_query_limit"]
55     if params[:limit]
56       if params[:limit].to_i.positive? && params[:limit].to_i <= max_limit
57         params[:limit].to_i
58       else
59         raise OSM::APIBadUserInput, "#{controller_name.classify} limit must be between 1 and #{max_limit}"
60       end
61     else
62       default_limit
63     end
64   end
65 end