]> git.openstreetmap.org Git - rails.git/blob - db/migrate/20120208122334_merge_acl_address_and_mask.rb
Merge pull request #4803 from tomhughes/preference-encoding
[rails.git] / db / migrate / 20120208122334_merge_acl_address_and_mask.rb
1 require "ipaddr"
2
3 class IPAddr
4   def address
5     _to_string(@addr)
6   end
7
8   def netmask
9     _to_string(@mask_addr)
10   end
11 end
12
13 class MergeAclAddressAndMask < ActiveRecord::Migration[4.2]
14   class Acl < ApplicationRecord
15   end
16
17   def up
18     Acl.find_each do |acl|
19       address = IPAddr.new(acl.address)
20       netmask = IPAddr.new(acl.netmask)
21       prefix = 0
22
23       while netmask != "0.0.0.0"
24         netmask <<= 1
25         prefix += 1
26       end
27
28       acl.address = "#{address.mask(prefix)}/#{prefix}"
29       acl.save!
30     end
31
32     remove_column :acls, :netmask
33   end
34
35   def down
36     add_column :acls, :netmask, :inet
37
38     Acl.find_each do |acl|
39       address = IPAddr.new(acl.address)
40
41       acl.address = address.address
42       acl.netmask = address.netmask
43       acl.save!
44     end
45
46     change_column :acls, :netmask, :inet, :null => false
47   end
48 end