Skip to content

Instantly share code, notes, and snippets.

@kopylovvlad
Created June 17, 2018 20:07
Show Gist options
  • Save kopylovvlad/bd25c7bb086ba54b3a79252a9e988f57 to your computer and use it in GitHub Desktop.
Save kopylovvlad/bd25c7bb086ba54b3a79252a9e988f57 to your computer and use it in GitHub Desktop.
# Before
module SearchService1
# Metrics/AbcSize: Assignment Branch Condition size for perform is too high.
# Metrics/CyclomaticComplexity: Cyclomatic complexity for perform is too high.
# Metrics/MethodLength: Method has too many lines.
# Metrics/PerceivedComplexity: Perceived complexity for perform is too high.
def self.perform(params = {})
scope = ::User.active
if params['id'].present?
scope = scope.where(id: params['id'])
end
%w[first_name last_name email city gender].each do |item|
next unless params[item].present?
scope = scope.where(item => params[item])
end
if params['height_after'].present?
scope = scope.where(height: { '$gt' => params['height_after'] })
end
if params['height_before'].present?
scope = scope.where(height: { '$lt' => params['height_before'] })
end
if params['weight_after'].present?
scope = scope.where(weight: { '$gt' => params['weight_after'] })
end
if params['weight_before'].present?
scope = scope.where(weight: { '$lt' => params['weight_before'] })
end
if params['gender'].present?
scope = scope.where(gender: params['gender'])
end
scope
end
end
# After
module SearchService2
PARAMS_MAP = {
'id' => ->(value) { { id: value } },
'first_name' => ->(value) { { 'first_name' => value } },
'last_name' => ->(value) { { 'last_name' => value } },
'email' => ->(value) { { 'email' => value } },
'city' => ->(value) { { 'city' => value } },
'gender' => ->(value) { { gender: value } },
'height_after' => ->(value) { { height: { '$gt' => value } } },
'height_before' => ->(value) { { height: { '$lt' => value } } },
'weight_after' => ->(value) { { weight: { '$gt' => value } } },
'weight_before' => ->(value) { { weight: { '$lt' => value } } },
}.freeze
def self.perform(params = {})
where_params = {}
PARAMS_MAP.keys.each do |item|
next unless params[item].present?
where_params.merge!(PARAMS_MAP[item][params[item]])
end
::User.active.where(where_params)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment