SHARE
TWEET

Untitled

a guest Apr 25th, 2019 74 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. module Iterations
  2.   module Queries
  3.     # Get specific iteration from suite by iteration parameters combination.
  4.     class SelectByParamsQuery
  5.       def initialize(combination: nil)
  6.         @combination = combination
  7.       end
  8.  
  9.       def results(scope)
  10.         db_format = { :$and => [] }
  11.  
  12.         combination.each do |key, val|
  13.           db_format[:$and] << bulletproof_value_format(key, val)
  14.         end
  15.  
  16.         scope
  17.           .where(db_format)
  18.       end
  19.  
  20.       private
  21.  
  22.       def bulletproof_value_format(key, val)
  23.         # Mongo behaves strangely. Value can be stored as integer or as string.
  24.         # In case it's stored as integer Mongo won't return records if we search it as string.
  25.         # We have to pass both options with $or operator so one of it will match value.
  26.         # E.g. {:$or=>[{"ip_0"=>25.0}, {"ip_0"=>/^\s*25\s*$/i}]}
  27.  
  28.         query_parts = []
  29.         query_parts << query_or_option(key, value_to_number(val))
  30.         query_parts << query_or_option(key, value_to_regexp(val))
  31.  
  32.         {:$or => query_parts}
  33.       end
  34.  
  35.       def query_or_option(key, value)
  36.         query = {}
  37.         query[key] = value
  38.         query
  39.       end
  40.  
  41.       def value_to_number(value)
  42.         return value.to_f if value =~ /^(\d+\.?\d*)$/
  43.         value
  44.       end
  45.  
  46.       def value_to_regexp(value)
  47.         # Case-insensitive search.
  48.         /^\s*#{Regexp.escape(value)}\s*$/i
  49.       end
  50.  
  51.       attr_reader :combination
  52.     end
  53.   end
  54. end
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top