diff --git a/app/models/screened_ip_address.rb b/app/models/screened_ip_address.rb index 7941543b33b..974e5baf798 100644 --- a/app/models/screened_ip_address.rb +++ b/app/models/screened_ip_address.rb @@ -26,6 +26,21 @@ class ScreenedIpAddress < ActiveRecord::Base self.errors.add(:ip_address, :invalid) end + # Return a string with the ip address and mask in standard format. e.g., "127.0.0.0/8". + # Ruby's IPAddr class has no method for getting this. + def ip_address_with_mask + if ip_address + mask = ip_address.instance_variable_get(:@mask_addr).to_s(2).count('1') + if mask == 32 + ip_address.to_s + else + "#{ip_address.to_s}/#{ip_address.instance_variable_get(:@mask_addr).to_s(2).count('1')}" + end + else + nil + end + end + def self.match_for_ip_address(ip_address) # The <<= operator on inet columns means "is contained within or equal to". # diff --git a/app/serializers/screened_ip_address_serializer.rb b/app/serializers/screened_ip_address_serializer.rb index 59c95bdfcc1..54e9922d58e 100644 --- a/app/serializers/screened_ip_address_serializer.rb +++ b/app/serializers/screened_ip_address_serializer.rb @@ -11,7 +11,7 @@ class ScreenedIpAddressSerializer < ApplicationSerializer end def ip_address - object.ip_address.try(:to_s) + object.ip_address_with_mask end end diff --git a/spec/models/screened_ip_address_spec.rb b/spec/models/screened_ip_address_spec.rb index 6f282a10be2..861ae8946ec 100644 --- a/spec/models/screened_ip_address_spec.rb +++ b/spec/models/screened_ip_address_spec.rb @@ -33,6 +33,20 @@ describe ScreenedIpAddress do end end + describe "ip_address_with_mask" do + it "returns nil when ip_address is nil" do + described_class.new.ip_address_with_mask.should be_nil + end + + it "returns ip_address without mask if there is no mask" do + described_class.new(ip_address: "123.123.23.22").ip_address_with_mask.should == "123.123.23.22" + end + + it "returns ip_address with mask" do + described_class.new(ip_address: "123.12.0.0/16").ip_address_with_mask.should == "123.12.0.0/16" + end + end + describe '#watch' do context 'ip_address is not being watched' do it 'should create a new record' do