Re: Encoded Columns and ActiveRecord

Peer Allan
Sat, 02 Jun 2007 15:48:13 -0000

Thanks Husein,

I think I will combining all the suggestions I have received on this
thread so that I end up with something like this:

class Address < ActiveRecord::Base

  require ''IPAddr''
  before_save :convert_ip

  def self.find_by_ip(value)
    find :first, :conditions => {:ip => IPAddr.new(value).to_i}
  end

  def ip
    convert_ip
    IPAddr.new(read_attribute(:ip), Socket::AF_INET).to_s
  end

  def ip=(value)
    write_attribute(:ip, IPAddr.new(value).to_i)
  end

  def convert_ip
    if read_attribute(:ip) =~ /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})?$/
      write_attribute(:ip, IPAddr.new(read_attribute(:ip)).to_i)
    end
  end

end

I just whipped this up so I obviously have not tested it in any way.

Peer


Husein Choroomi wrote:
> require ''ipaddr''
>
> # INET_ATON
> IPAddr.new("192.168.0.10").to_i # => 3232235530
>
> # INET_NTOA
> IPAddr.new(3232235530, Socket::AF_INET).to_s # =>
"192.168.0.10"
>
> HTH
> - H
>
> On 6/2/07, Peer Allan
<rails-mailing-list-ARtvInVfO7ksV2N9l4h3zg@public.gmane.org> wrote:
>> using 4 bytes instead of 15 will really add up over time.  (Yes, I know
>> > On Fri, 2007-06-01 at 22:47 +0200, Peer Allan wrote:
>> >
>> >
>> --
>> Posted via http://www.ruby-forum.com/.
>>
>> >
>>
>
>
> --
> Husein Choroomi
> Yucca Intelligence Development
> http://www.YuccaHQ.com