/ip_addresses: allow grouping IPs by subnet.

This commit is contained in:
evazion
2019-11-11 19:41:09 -06:00
parent bf6bb94702
commit 68e1140b0d
4 changed files with 28 additions and 7 deletions

View File

@@ -14,14 +14,31 @@ class IpAddress < ApplicationRecord
q.order(created_at: :desc)
end
def self.group_by_ip_addr
group(:ip_addr).select("ip_addr, COUNT(*) AS count_all").reorder("count_all DESC, ip_addr")
def self.group_by_ip_addr(ipv4_masklen = nil, ipv6_masklen = nil)
ipv4_masklen ||= 32
ipv6_masklen ||= 128
q = select(sanitize_sql([<<~SQL, ipv4_masklen, ipv6_masklen]))
CASE
WHEN family(ip_addr) = 4
THEN network(set_masklen(ip_addr, ?))
ELSE network(set_masklen(ip_addr, ?))
END AS ip_addr,
COUNT(*) AS count_all
SQL
q.group("1").reorder("count_all DESC, ip_addr")
end
def self.group_by_user
group(:user_id).select("user_id, COUNT(*) AS count_all").reorder("count_all DESC, user_id")
end
def to_s
# include the subnet mask only when the IP denotes a subnet.
ip_addr.size > 1 ? ip_addr.to_string : ip_addr.to_s
end
def readonly?
true
end