Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add type coercion support to Prefix #96

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions lib/ipaddress/prefix.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,30 @@ def to_s
def to_i
@prefix
end
alias_method :to_int, :to_i

#
# Provides support for Ruby type coercion
#
def coerce(other)
case other
when Integer
[other, @prefix]
else
other.coerce(@prefix).reverse!
end
end

#
# Compare the prefix
#
def <=>(oth)
@prefix <=> oth.to_i
if oth.is_a? Integer
@prefix <=> oth
else
x, y = oth.coerce(@prefix)
x <=> y
end
end

#
Expand All @@ -61,7 +79,8 @@ def +(oth)
if oth.is_a? Integer
self.prefix + oth
else
self.prefix + oth.prefix
x, y = oth.coerce(@prefix)
x + y
end
end

Expand All @@ -74,7 +93,8 @@ def -(oth)
if oth.is_a? Integer
self.prefix - oth
else
(self.prefix - oth.prefix).abs
x, y = oth.coerce(@prefix)
x - y
end
end

Expand Down
20 changes: 19 additions & 1 deletion test/ipaddress/prefix_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -73,19 +73,37 @@ def test_method_to_u32
end
end

def test_method_cmp
p1 = @klass.new 8
p2 = @klass.new 24
assert_equal false, (p1 > 16)
assert_equal true, (p2 > 16)
assert_equal true, (16 >= p1)
assert_equal false, (16 >= p2)
assert_equal true, (p1 < p2)
assert_equal true, (p1 == 8r)
assert_equal true, (24r == p2)
end

def test_method_plus
p1 = @klass.new 8
p2 = @klass.new 10
assert_equal 18, p1+p2
assert_equal 12, p1+4
assert_equal 14r, p2+4r
assert_equal 12r, 4r+p1
end

def test_method_minus
p1 = @klass.new 8
p2 = @klass.new 24
assert_equal 16, p1-p2
assert_equal -16, p1-p2
assert_equal 16, p2-p1
assert_equal 20, p2-4
assert_equal 20r, p2-4r
assert_equal 24, 32-p1
assert_equal 8, 32-p2
assert_equal 8r, 32r-p2
end

def test_initialize
Expand Down