Skip to content

Instantly share code, notes, and snippets.

@ostaptan
Last active July 3, 2018 13:20
Show Gist options
  • Select an option

  • Save ostaptan/f1603770e65c79469269f3ce2d191c4c to your computer and use it in GitHub Desktop.

Select an option

Save ostaptan/f1603770e65c79469269f3ce2d191c4c to your computer and use it in GitHub Desktop.
supermeta
module Statistics
class GenderAgeQuery
attr_accessor :location_id, :errors, :total_count, :male_count, :female_count
META_METHODS = {}
[[0, 18],
[18, 29],
[30, 44],
[45, 60],
[60, 0]].each do |range|
META_METHODS["from_#{range[0]}_to_#{range[1]}"] = range
META_METHODS["from_#{range[0]}_to_#{range[1]}_male"] = range
META_METHODS["from_#{range[0]}_to_#{range[1]}_female"] = range
end
META_METHODS.each do |method_name, range|
define_method(method_name.to_sym) do |*args|
query = "sessions.location_id = #{@location_id}"
query += " AND people.age_from = #{range[0]}" if range[0] > 0
query += " AND people.age_to = #{range[1]}" if range[1] > 0
suffix = method_name.split('_').last
if %(male female).include?(suffix)
query += " AND (people.gender like '#{suffix}' OR social_networks.gender like '#{suffix}')"
Person.joins(:sessions).joins(:social_networks).where(query).uniq.count
else
Person.joins(:sessions).where(query).uniq.count
end
end
end
def initialize(args)
@args = args.with_indifferent_access
@location_id = @args[:location_id]
META_METHODS.keys.each do |method_name|
self.class.send(:define_method, "#{method_name}=".to_sym) do |value|
instance_variable_set("@" + "#{method_name}".to_s, value)
end
end
end
def call
META_METHODS.keys + %w(total_count male_count female_count unknown_count).each do |method_name|
self.send("#{method_name}=", send(method_name))
end
self
end
private
def total_count
Session.where(location_id: @location_id).count
end
%w(male female).each do |method_name|
define_method("#{method_name}_count") do |*args|
Person.joins(:sessions).joins(:social_networks)
.where("sessions.location_id = ? AND (people.gender like '#{method_name}' OR social_networks.gender like '#{method_name}')", @location_id)
.uniq.count
end
end
def unknown_count
total_count - male_count - female_count
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment