Skip to content

Instantly share code, notes, and snippets.

@rossmari
Last active August 29, 2015 14:06
Show Gist options
  • Save rossmari/652f4fe065a9d44c6a0c to your computer and use it in GitHub Desktop.
Save rossmari/652f4fe065a9d44c6a0c to your computer and use it in GitHub Desktop.
search params processor for sliders
class VillagesSliderFilter
VILLAGE_SORT_PARAMS = { price: { range: true },
distance: { range: false },
area_price: { range: false },
land_price: { range: true } }
VILLAGE_JOINS = [:builders, :village_odds, :building_types, :directions]
def initialize(params)
@params = params
end
def process_params
# remove empty hashes, arrays, etc from params
clear_params_hash(@params)
VILLAGE_SORT_PARAMS.each do |key, param|
if param[:range]
instance_variable_set("@#{key.to_s}_start", @params.delete("#{key}_start".to_sym))
instance_variable_set("@#{key.to_s}_stop", @params.delete("#{key}_stop".to_sym))
else
instance_variable_set("@#{key}", @params.delete(key))
end
end
end
def search
villages = Village.joins(VILLAGE_JOINS).where(@params)
VILLAGE_SORT_PARAMS.each do |key, param|
start = instance_variable_get("@#{key}_start")
stop = instance_variable_get("@#{key}_stop")
if start && stop
if param[:range]
villages = villages.where("#{key}_start >= ? AND #{key}_stop <= ?", start, stop)
else
villages = villages.where("#{key} >= ? AND #{key} <= ?", start, stop)
end
end
end
return villages.uniq
end
def clear_params_hash(hash)
hash.delete_if do |k, v|
if v.empty?
true
else
if v.is_a? Hash
clear_params_hash(v).empty?
elsif v.is_a? Array
clear_params_array(v).empty?
end
end
end
end
def clear_params_array(array)
array.delete_if{|value| value.empty?}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment