Skip to content

Commit

Permalink
Don't include ellipsis in truncated digest output
Browse files Browse the repository at this point in the history
Using truncate to limit the length of the digest has the unwanted side
effect of adding an ellipsis when the input is longer than the limit.

Also don't instantiate a new object for every digest.

Inspired by
rails/rails@b9e7c67
  • Loading branch information
iNecas committed May 11, 2018
1 parent 475d689 commit 57ebb76
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 16 deletions.
10 changes: 1 addition & 9 deletions lib/deface/digest.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,8 @@ def digest_class=(klass)
end

def hexdigest(arg)
new.hexdigest(arg)
@digest_class.hexdigest(arg)[0...32]
end
end

def initialize(klass = nil)
@digest_class = klass || self.class.digest_class
end

def hexdigest(arg)
@digest_class.hexdigest(arg).truncate(32)
end
end
end
25 changes: 18 additions & 7 deletions spec/deface/digest_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,31 @@

module Deface
describe Digest do
def with_custom_digest
digest = double("digest")
original_digest = Digest.digest_class
Digest.digest_class = digest
yield digest
ensure
Digest.digest_class = original_digest
end

it "should use MD5 by default" do
expect(Digest.new.hexdigest("123")).to eq "202cb962ac59075b964b07152d234b70"
expect(Digest.hexdigest("123")).to eq "202cb962ac59075b964b07152d234b70"
end

it "should use user-provided digest" do
digest = double("digest")
expect(digest).to receive(:hexdigest).with("to_digest").and_return("digested")
expect(Digest.new(digest).hexdigest("to_digest")).to eq "digested"
with_custom_digest do |digest|
expect(digest).to receive(:hexdigest).with("to_digest").and_return("digested")
expect(Digest.hexdigest("to_digest")).to eq "digested"
end
end

it "should truncate digest to 32 characters" do
digest = double("digest")
expect(digest).to receive(:hexdigest).with("to_digest").and_return("a" * 50)
expect(Digest.new(digest).hexdigest("to_digest").size).to eq 32
with_custom_digest do |digest|
expect(digest).to receive(:hexdigest).with("to_digest").and_return("a" * 50)
expect(Digest.hexdigest("to_digest").size).to eq 32
end
end
end
end
Expand Down

0 comments on commit 57ebb76

Please sign in to comment.