Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- module Iterations
- module Queries
- # Get specific iteration from suite by iteration parameters combination.
- class SelectByParamsQuery
- def initialize(combination: nil)
- @combination = combination
- end
- def results(scope)
- db_format = { :$and => [] }
- combination.each do |key, val|
- db_format[:$and] << bulletproof_value_format(key, val)
- end
- scope
- .where(db_format)
- end
- private
- def bulletproof_value_format(key, val)
- # Mongo behaves strangely. Value can be stored as integer or as string.
- # In case it's stored as integer Mongo won't return records if we search it as string.
- # We have to pass both options with $or operator so one of it will match value.
- # E.g. {:$or=>[{"ip_0"=>25.0}, {"ip_0"=>/^\s*25\s*$/i}]}
- query_parts = []
- query_parts << query_or_option(key, value_to_number(val))
- query_parts << query_or_option(key, value_to_regexp(val))
- {:$or => query_parts}
- end
- def query_or_option(key, value)
- query = {}
- query[key] = value
- query
- end
- def value_to_number(value)
- return value.to_f if value =~ /^(\d+\.?\d*)$/
- value
- end
- def value_to_regexp(value)
- # Case-insensitive search.
- /^\s*#{Regexp.escape(value)}\s*$/i
- end
- attr_reader :combination
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement