aboutsummaryrefslogblamecommitdiffstats
path: root/activerecord/lib/active_record/connection_adapters/postgresql/oid/cidr.rb
blob: a53b4ee8e213d1d2214eb7f0bfaf2b8dd99c7a28 (plain) (tree)
1
2
3
4
5
6
7
8
9



                           
                                          



                  










                                                                   







                                                                                            
                               










                                  





             
module ActiveRecord
  module ConnectionAdapters
    module PostgreSQL
      module OID # :nodoc:
        class Cidr < Type::Value # :nodoc:
          def type
            :cidr
          end

          def type_cast_for_schema(value)
            subnet_mask = value.instance_variable_get(:@mask_addr)

            # If the subnet mask is equal to /32, don't output it
            if subnet_mask == (2**32 - 1)
              "\"#{value.to_s}\""
            else
              "\"#{value.to_s}/#{subnet_mask.to_s(2).count('1')}\""
            end
          end

          def type_cast_for_database(value)
            if IPAddr === value
              "#{value.to_s}/#{value.instance_variable_get(:@mask_addr).to_s(2).count('1')}"
            else
              value
            end
          end

          def cast_value(value)
            if value.nil?
              nil
            elsif String === value
              begin
                IPAddr.new(value)
              rescue ArgumentError
                nil
              end
            else
              value
            end
          end
        end
      end
    end
  end
end