added node class

This commit is contained in:
Karl Seguin 2011-08-09 21:45:36 +08:00 committed by Kyle Banker
parent d552d603a8
commit 2557a575eb
3 changed files with 69 additions and 0 deletions

View File

@ -63,6 +63,7 @@ require 'mongo/util/uri_parser'
require 'mongo/collection'
require 'mongo/connection'
require 'mongo/repl_set_connection'
require 'mongo/node'
require 'mongo/cursor'
require 'mongo/db'
require 'mongo/exceptions'

19
lib/mongo/node.rb Normal file
View File

@ -0,0 +1,19 @@
module Mongo
class Node
attr_accessor :host, :port, :address
def initialize(data)
data = data.split(':') if data.is_a?(String)
self.host = data[0]
self.port = data[1] ? data[1].to_i : Connection::DEFAULT_PORT
self.address = "#{host}:#{port}"
end
def eql?(other)
other.is_a?(Node) && host == other.host && port == other.port
end
alias :== :eql?
def hash
address.hash
end
end
end

49
test/unit/node_test.rb Normal file
View File

@ -0,0 +1,49 @@
require './test/test_helper'
class NodeTest < Test::Unit::TestCase
should "load a node from an array" do
node = Node.new(['power.level.com', 9001])
assert_equal 'power.level.com', node.host
assert_equal 9001, node.port
assert_equal 'power.level.com:9001', node.address
end
should "should default the port for an array" do
node = Node.new(['power.level.com'])
assert_equal 'power.level.com', node.host
assert_equal Connection::DEFAULT_PORT, node.port
assert_equal "power.level.com:#{Connection::DEFAULT_PORT}", node.address
end
should "load a node from a stirng" do
node = Node.new('localhost:1234')
assert_equal 'localhost', node.host
assert_equal 1234, node.port
assert_equal 'localhost:1234', node.address
end
should "should default the port for a string" do
node = Node.new('192.168.0.1')
assert_equal '192.168.0.1', node.host
assert_equal Connection::DEFAULT_PORT, node.port
assert_equal "192.168.0.1:#{Connection::DEFAULT_PORT}", node.address
end
should "two nodes with the same address should be equal" do
assert_equal Node.new('192.168.0.1'), Node.new(['192.168.0.1', Connection::DEFAULT_PORT])
end
should "two nodes with the same address should have the same hash" do
assert_equal Node.new('192.168.0.1').hash, Node.new(['192.168.0.1', Connection::DEFAULT_PORT]).hash
end
should "two nodes with different addresses should not be equal" do
assert_not_equal Node.new('192.168.0.2'), Node.new(['192.168.0.1', Connection::DEFAULT_PORT])
end
should "two nodes with the same address should have the same hash" do
assert_not_equal Node.new('192.168.0.1').hash, Node.new('1239.33.4.2393:29949').hash
end
end