Skip to content

Instantly share code, notes, and snippets.

@yellow5
Created February 2, 2011 21:15
Show Gist options
  • Save yellow5/808456 to your computer and use it in GitHub Desktop.
Save yellow5/808456 to your computer and use it in GitHub Desktop.
Meant for a rails controller; provides actions to convert ipv4 addresses to integers and vice versa
module IpConversionTools
def self.included(base)
base.class_eval do
helper_method :ip_to_i
helper_method :ip_to_s
end
end
protected
def ip_to_i(ip=nil)
begin
IPAddr.new(ip).to_i
rescue
0
end
end
def ip_to_s(ip=nil)
begin
IPAddr.new(ip, Socket::AF_INET).to_s
rescue
'0.0.0.0'
end
end
end
require 'spec/spec_helper'
describe IpConversionTools do
class IpConversionToolsTestController < ApplicationController
include IpConversionTools
end
subject { IpConversionToolsTestController.new }
context 'ip_to_i' do
def do_invoke(ip=nil)
subject.send(:ip_to_i, ip)
end
it 'should return a Fixnum' do
do_invoke.class.should == Fixnum
end
it 'should return 0 if the ip received is nil' do
do_invoke(nil).should == 0
end
it 'should return 0 if the ip received is a string but not an ip address' do
do_invoke('bad_ip').should == 0
end
it 'should return an integer representation of the ip received' do
do_invoke('127.0.0.1').should == 2130706433
end
end
context 'ip_to_s' do
def do_invoke(ip=nil)
subject.send(:ip_to_s, ip)
end
it 'should return a string' do
do_invoke.class.should == String
end
it 'should return empty ip if it receives a string argument' do
do_invoke('').should == '0.0.0.0'
end
it 'should return a string representation of the ip received' do
do_invoke(2130706433).should == '127.0.0.1'
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment