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

Allow using Binary as hash keys. #23

Merged
merged 1 commit into from
Jan 22, 2015
Merged
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
12 changes: 12 additions & 0 deletions lib/bson/binary.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,18 @@ def ==(other)
return false unless other.is_a?(Binary)
type == other.type && data == other.data
end
alias eql? ==

# Generates a Fixnum hash value for this object.
#
# Allows using Binary as hash keys.
#
# @return [ Fixnum ]
#
# @since 2.3.1
def hash
data.hash + type.hash
end

# Get the binary as JSON hash data.
#
Expand Down
38 changes: 38 additions & 0 deletions spec/bson/binary_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,44 @@
require "spec_helper"

describe BSON::Binary do
let(:testing1) { described_class.new("testing") }
let(:testing2) { described_class.new("testing") }
let(:not_testing) { described_class.new("not testing") }

describe "#eql?" do
context "for two equal objects" do
it "returns true" do
expect(testing1).to eql(testing2)
end
end

context "for two different objects" do
it "returns false" do
expect(testing1).not_to eql(not_testing)
end
end
end

describe "#hash" do
context "for two equal objects" do
it "is the same" do
expect(testing1.hash).to eq(testing2.hash)
end
end

context "for two different objects" do
it "is different" do
expect(testing1.hash).not_to eq(not_testing.hash)
end
end
end

let(:hash) do { testing1 => "my value" } end

it "can be used as Hash key" do
expect(hash[testing2]).to eq("my value")
expect(hash[not_testing]).to be_nil
end

describe "#as_json" do

Expand Down