Module: HasIpAddress::ClassMethods

Defined in:
lib/has_ip_address.rb

Instance Method Summary collapse

Instance Method Details

#has_ip_address(column = :ip_address) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/has_ip_address.rb', line 13

def has_ip_address(column = :ip_address)
  define_method "#{column}=" do |address|
    ipaddr = address.to_ipaddr
    write_attribute column, ipaddr

    ipaddr
  end

  define_method column do
    integer = read_attribute column
    if integer.present?
      IPAddr.new(i_to_ipaddr(integer))
    end
  end

  unless self.instance_methods.include?('i_to_ipaddr')
    define_method :i_to_ipaddr do |i|
      [24, 16, 8, 0].collect {|b| (i >> b) & 255}.join('.')
    end
  end      
end