discourse/lib/freedom_patches/ip_addr.rb
Alan Guo Xiang Tan ab2c17236a DEV: Follow Discourse's convention when monkey patching.
Having to load `ip_addr` is confusing especially when that file exists
to monkey patch Ruby's `IpAddr` class. Moving it to our freedom patches
folder which is automatically loaded on initialization.
2022-01-11 09:48:27 +08:00

38 lines
681 B
Ruby

# frozen_string_literal: true
class IPAddr
def self.handle_wildcards(val)
return if val.blank?
num_wildcards = val.count('*')
return val if num_wildcards == 0
# strip ranges like "/16" from the end if present
v = val.gsub(/\/.*/, '')
return if v[v.index('*')..-1] =~ /[^\.\*]/
parts = v.split('.')
(4 - parts.size).times { parts << '*' } # support strings like 192.*
v = parts.join('.')
"#{v.tr('*', '0')}/#{32 - (v.count('*') * 8)}"
end
def to_cidr_s
if @addr
mask = @mask_addr.to_s(2).count('1')
if mask == 32
to_s
else
"#{to_s}/#{mask}"
end
else
nil
end
end
end