1 # Mixin module for reading out query parameters from request params.
6 # @where, @filters, @limit, @offset, @orders
9 # Default limit on number of rows to return in a single query.
12 # Load params[:where] into @where
14 if params[:where].nil? or params[:where] == ""
16 elsif params[:where].is_a? Hash
17 @where = params[:where]
18 elsif params[:where].is_a? String
20 @where = Oj.load(params[:where])
21 raise unless @where.is_a? Hash
23 raise ArgumentError.new("Could not parse \"where\" param as an object")
26 @where = @where.with_indifferent_access
29 # Load params[:filters] into @filters
30 def load_filters_param
32 if params[:filters].is_a? Array
33 @filters += params[:filters]
34 elsif params[:filters].is_a? String and !params[:filters].empty?
36 f = Oj.load params[:filters]
38 raise unless f.is_a? Array
42 raise ArgumentError.new("Could not parse \"filters\" param as an array")
48 ["#{table_name}.modified_at desc"]
51 # Load params[:limit], params[:offset] and params[:order]
52 # into @limit, @offset, @orders
53 def load_limit_offset_order_params
55 unless params[:limit].to_s.match(/^\d+$/)
56 raise ArgumentError.new("Invalid value for limit parameter")
58 @limit = params[:limit].to_i
60 @limit = DEFAULT_LIMIT
64 unless params[:offset].to_s.match(/^\d+$/)
65 raise ArgumentError.new("Invalid value for offset parameter")
67 @offset = params[:offset].to_i
73 if (params[:order].is_a?(Array) && !params[:order].empty?) || !params[:order].blank?
77 if params[:order].starts_with? '['
78 od = Oj.load(params[:order])
79 raise unless od.is_a? Array
82 params[:order].split(',')
90 attr, direction = order.strip.split " "
92 if attr.match /^[a-z][_a-z0-9]+$/ and
93 model_class.columns.collect(&:name).index(attr) and
94 ['asc','desc'].index direction.downcase
95 @orders << "#{table_name}.#{attr} #{direction.downcase}"
96 elsif attr.match /^([a-z][_a-z0-9]+)\.([a-z][_a-z0-9]+)$/
97 @orders << "#{attr} #{direction.downcase}"
103 @orders = default_orders
108 @select = params[:select]
111 @select = Oj.load params[:select]
112 raise unless @select.is_a? Array or @select.nil?
114 raise ArgumentError.new("Could not parse \"select\" param as an array")
119 # Any ordering columns must be selected when doing select,
120 # otherwise it is an SQL error, so filter out invaliding orderings.
121 @orders.select! { |o|
122 # match select column against order array entry
123 @select.select { |s| /^#{table_name}.#{s}( (asc|desc))?$/.match o }.any?
127 @distinct = true if (params[:distinct] == true || params[:distinct] == "true")
128 @distinct = false if (params[:distinct] == false || params[:distinct] == "false")